Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Hi all..

In today’s post I will show you how to add actionbar tabs dynamically, remove one by one , hide and unhide them, removing all tabs at once etc.

This simple java code does that.

First create a project and in the MainActivity, paste this.

package com.coderzheaven.actionbartabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action_bar_tabs); 
    }

    public void onAddTab(View v) {
        final ActionBar bar = getActionBar();
        final int tabCount = bar.getTabCount();
        final String text = "Tab " + tabCount;
        bar.addTab(bar.newTab()
                .setText(text)
                .setTabListener(new TabListener(new TabContentFragment(text))));
    }

    public void onRemoveTab(View v) {
        final ActionBar bar = getActionBar();
        if(bar.getTabCount() > 0)
        	bar.removeTabAt(bar.getTabCount() - 1);
    }

    public void onToggleTabs(View v) {
        final ActionBar bar = getActionBar();

        if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
        } else {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        }
    }

    public void onRemoveAllTabs(View v) {
        getActionBar().removeAllTabs();
    }

    /**
     * A TabListener receives event callbacks from the action bar as tabs
     * are deselected, selected, and reselected. 
     **/
    private class TabListener implements ActionBar.TabListener {
        private TabContentFragment mFragment;

        public TabListener(TabContentFragment fragment) {
            mFragment = fragment;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.add(R.id.fragment_content, mFragment, mFragment.getText());
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(mFragment);
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(MainActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }

    private class TabContentFragment extends Fragment {
        private String mText;

        public TabContentFragment(String text) {
            mText = text;
        }

        public String getText() {
            return mText;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false);

            TextView text = (TextView) fragView.findViewById(R.id.text);
            text.setText(mText);

            return fragView;
        }
    }
}

You may be getting many errors, we will be resolving all that in just a few minutes.

Now create an xml named “action_bar_tabs.xml” inside the res/layout folder and copy this code into it.

<?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">
    <FrameLayout android:id="@+id/fragment_content"
                 android:layout_width="match_parent"
                 android:layout_height="0dip"
                 android:layout_weight="1" />
    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="0dip"
                  android:layout_weight="1"
                  android:orientation="vertical">
        <Button android:id="@+id/btn_add_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add Tab"
                android:onClick="onAddTab" />
        <Button android:id="@+id/btn_remove_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove Tab"
                android:onClick="onRemoveTab" />
        <Button android:id="@+id/btn_toggle_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Toggle Tabs"
                android:onClick="onToggleTabs" />
        <Button android:id="@+id/btn_remove_all_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove All Tabs"
                android:onClick="onRemoveAllTabs" />
    </LinearLayout>
</LinearLayout>

Now create another xml for the tab content and named it “action_bar_tab_content.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

OK Done. Go on and run it.

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

Download Source code from here

Download.

Please leave your valuable comments now

How to create a Slide from Left animation while deleting a row from a ListView in Android?

Hello all……

I have written a lost of posts on Listviews. You can see that by just searching Listviews in my site. Today I will show you how to create a slide out animation while we delete a row from a ListView.

So this is the xml that contains the ListView. Let it be in the main.xml

main.xml

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

Create another file inside the layout folder named “simplerow.xml”.

simplerow.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/rowTextView" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
 android:padding="10dp"
 android:textSize="16sp" >
</TextView>

OK our xml part is over. Now the java part.

This is the main java file that implements this xml.

“SimpleListViewActivity.java”

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListViewActivity extends Activity {
  
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
   ArrayList<String> all_planets = 
       new ArrayList<String>(){      
           private static final long serialVersionUID = -1773393753338094625L;
           {
               add("Mercury ");
               add("Venus "); 
               add("Earth"); 
               add("Mars"); 
               add("Jupiter"); 
               add("Saturn"); 
               add("Uranus"); 
               add("Neptune"); 
               add("Pluto"); 
           }
   };
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    
  
    mainListView = (ListView) findViewById( R.id.mainListView );

    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, all_planets);

    mainListView.setAdapter( listAdapter );  
    
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View rowView, int positon,long id) {
            Toast.makeText(rowView.getContext(), ""+positon, Toast.LENGTH_LONG).show();
            removeListItem(rowView,positon);
        }
    });
    
  }
  
  protected void removeListItem(View rowView, final int positon) {

      final Animation animation = AnimationUtils.loadAnimation(SimpleListViewActivity.this,android.R.anim.slide_out_right); 
      rowView.startAnimation(animation);
      Handler handle = new Handler();
      handle.postDelayed(new Runnable() {

		@Override
          public void run() {
        	  all_planets.remove(positon);
              listAdapter.notifyDataSetChanged();
              animation.cancel();
          }
      },1000);

  }

}

OK Done. Now run it and see the result.

Slide delete

Slide delete

Slide delete

Join the Forum discussion on this post

Download.

How to start with ActionBar in Android?

With Android 3.0 Google eliminated the need of hardware menu button which is replaced by Action Bars.

Here is a quick example on how to use ActionBars.

Action Bar in Android

First create a new project and name it ActionBarExample.

Now create a folder named “menu” in res folder and create a new XML file inside it named “action_bar_menu.xml”.

action_bar_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menuitem1" android:showAsAction="ifRoom" android:title="Test1"></item>
    <item android:id="@+id/menuitem2" android:showAsAction="ifRoom" android:title="Test2"></item>
</menu>

Now the java code for implementing this ActionBar.

MainActivity.java

package com.example.actionbarexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
	@Override
	  public void onCreate(Bundle savedInstanceState) {   
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	  }

	  @Override
	  public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.action_bar_menu, menu);
	    return true;
	  }

	  @Override
	  public boolean    onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menuitem1:
	      Toast.makeText(this, "Test 1 Clicked", Toast.LENGTH_SHORT).show();
	      break;
	    case R.id.menuitem2:
	      Toast.makeText(this, "Test 2 Clicked", Toast.LENGTH_SHORT).show();
	      break;

	    default:
	      break;
	    }

	    return true;
	  }
	} 

As there is enough space in the ActionBar otherwise you may see the Overflow menu or you have to use the Option menu button on your phone.

Please leave your comments om this post.

How to change the hint text color in android?

Hello all..

This simple example will show you how to change the hint text color in android

Here is the java code to simply do this.

youredittext.setHint(Html.fromHtml("<font color='#FF0000'>Hello</font> "));

here is a sample project to view the difference.

This is the contents of the main java file.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.EditText;

public class HintColorDemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);

          EditText ed = (EditText)findViewById(R.id.editText1);
          ed.setHint("Hello ");

          EditText ed2 = (EditText)findViewById(R.id.editText2);
          ed2.setHint(Html.fromHtml("<font color='#FF0000'>Hello</font> "));
     }
}

The main.xml file

<?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" >

     <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/hello" />

     <EditText
          android:id="@+id/editText1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:ems="10" >

          <requestFocus />
     </EditText>

     <EditText
          android:id="@+id/editText2"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:ems="10" >
     </EditText>
</LinearLayout>


Here I am setting a read color to the second edittext hint.
See the screenshot.

Please leave your comments if you found this useful.

Passing data between Intents or classes in ANDROID?

Many of our application reqiures sending data from one intent to another.
This is done by putting data into one intent using putExtras() and getting it in the other intent using the getExtras() which matches the string value. However you can pass string, boolean, integer etc between intents.
For passing data between intents you need atleast two intents.
Here the two activities are named DataBetweenIntentsExample and Result
Make sure to add the two activities in your manifest file, otherwise your application will force close.
Here is an example showing how to pass data between intents in ANDROID.
First we create the layout.
Here I am crearting a simple layout with only one button and a textBox in it.
The main.xml file looks like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
	android:text="Site Name : "
	android:id="@+id/TV1"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</TextView>

<EditText
	android:text=""
	android:id="@+id/site_name"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</EditText>

<Button
	android:text=" Send Data "
	android:id="@+id/B1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</Button>

</LinearLayout>

Then you create a java file named Result.xml and place it inside the current package.
Then create a layout for the Result.xml file and name it result.xml and place it in the layout directory.

The result.xml file will look like this

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

</LinearLayout>

Then we go to the main java file DataBetweenIntentsExample.java and copy this code into it.

package pack.DataBetweenIntents;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class DataBetweenIntentsExample extends Activity {

	public Button B1;
	public EditText T1;
	public Intent intent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        B1 = (Button)findViewById(R.id.B1);
        T1 = (EditText)findViewById(R.id.site_name);

        intent = new Intent();
		intent.setClass(this,Result.class);

        B1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				intent.putExtra("site_name",T1.getText().toString());
				startActivity(intent);

			}
		});
    }
}

Now copy the following code to Result.java file.

package pack.DataBetweenIntents;

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

public class Result extends Activity {

	public TextView TV;
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.result);

	        TV = (TextView)findViewById(R.id.result_tv);
	        Bundle bundle = getIntent().getExtras();

	        if(bundle.getString("cancel") != null){
	        	TV.setText("Cancelled");
	        }else{
	        	String txt1 = bundle.getString("site_name");
	        	TV.setText("Data send from previous intent nSite Name = " + txt1 );
	        }
	    }
}

Androidmanifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.DataBetweenIntents"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DataBetweenIntentsExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Result"
         		  android:label="Results"
        />
</manifest>

Saving TextFile to SDCARD in android?

Hello android lovers,

In today’s tutorial I will show you how to

1. Create a text file and save a textfile in your SDCARD in your preferred path.

2. Read the contents from the same file and show it in a TextView.

For writing a file we use the FileWriter class and for reading the textfile we use the FileReader class.
Now Let’s check out how we do this .

First create a fresh project and name it “saveFileDemo”.
In the “saveFileDemo.java” file copy this contents.

package com.coderzheaven.pack;

import java.io.FileReader;
import java.io.FileWriter;

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

public class saveFileDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        String file_contents = readFile();
    	System.out.println("FILE CONTENTS :  "  + file_contents);

    	TextView tv = (TextView)findViewById(R.id.tv);
    	tv.setText("Read File contents from SDCARD : n" + file_contents);
    }
    public void createFile(){
    	FileWriter fWriter;
        try{
             fWriter = new FileWriter("/sdcard/myfile.txt");
             fWriter.write("My file contents");
             fWriter.flush();
             fWriter.close();
         }catch(Exception e){
                  e.printStackTrace();
         }
    }
    public String readFile(){
        char buf[] = new char[512];
        FileReader rdr;
        String contents = "";
		try {
			rdr = new FileReader("/sdcard/myfile.txt");
			int s = rdr.read(buf);
			for(int k = 0; k < s; k++){
				contents+=buf[k];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contents;
    }
}

This is the main.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
	android:id = "@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

Here is the Strings.xml file contents

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, saveFileDemo!</string>
    <string name="app_name">saveFileDemo from Coderzheaven</string>
</resources>

Now the AndroidManifest.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".saveFileDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


You can actually see the file by going to the FileExplorer and expanding the mnt folder(or simply SDCARD in older versions) and the SDCARD folder.
See the screenshot.

Check this link to see the contents of this file manually.

Please leave your valuable comments on this post.

Parsing an XML from Online in Android

In the previous example I showed how to parse an xml that is stored in a file in res/xml folder.
In this post I will show you how to parse an xml that is stored in a server in an xml file.

Here I am using an xml that is stored in here

Here is the java code for that.

First create a fresh project and name it ParseXMLDemo

Then in the ParseXMLDemo.java file copy this code

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ParseXMLDemo extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = ParseXMLMethods.getXML();
        Document doc = ParseXMLMethods.XMLfromString(xml);

        int numResults = ParseXMLMethods.numResults(doc);

        if((numResults <= 0)){
        	Toast.makeText(ParseXMLDemo.this, "There is no data in the xml file", Toast.LENGTH_LONG).show();
        	finish();
        }

		NodeList children = doc.getElementsByTagName("os");

		for (int i = 0; i < children.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element)children.item(i);
			map.put("id", ParseXMLMethods.getValue(e, "id"));
        	map.put("name", ParseXMLMethods.getValue(e, "name"));
        	map.put("site", ParseXMLMethods.getValue(e, "site"));
        	mylist.add(map);
		}

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_layout,
                        new String[] { "name", "site" },
                        new int[] { R.id.title, R.id.subtitle});

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		@SuppressWarnings("unchecked")
				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
        		Toast.makeText(ParseXMLDemo.this,o.get("name"), Toast.LENGTH_LONG).show();
			}
		});
    }
}

Now create another java file inside the src folder and name it ParseXMLMethods.java and copy this contents into it.

package com.coderzheaven.pack;

import java.io.IOException;
import java.io.StringReader;
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.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;


public class ParseXMLMethods {

	public final static Document XMLfromString(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) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
        return doc;
	}

	 public final static String getElementValue( Node elem ) {
	     Node kid;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
	                     return kid.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	 public static String getXML(){
			String line = null;

			try {

				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost("http://coderzheaven.com/xml/test.xml");

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

			} catch (Exception e) {
				line = "Internet Connection Error >> " + e.getMessage();
			}
			return line;
	}

	public static int numResults(Document doc){
		Node results = doc.getDocumentElement();
		int res = -1;
		try{
			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
		}catch(Exception e ){
			res = -1;
		}
		return res;
	}

	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return ParseXMLMethods.getElementValue(n.item(0));
	}
}

Now the main layout file main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView
	 	android:id="@id/android:list"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_weight="1"
	    android:background="#FF0000"
	 	android:drawSelectorOnTop="false" />
</LinearLayout>

Create another file named list_layout.xml inside the layout folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    >
<TextView
	android:id="@+id/title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp"
    android:textStyle="bold"
    />
    <TextView
	android:id="@+id/subtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:textSize="14dp"
    android:textColor="#000000" />
</LinearLayout>

This is the Strings.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ParseXMLDemo!</string>
    <string name="app_name">ParseXMLDemo Coderzheaven.com</string>
</resources>

Now you are done go on and run the application.

Parse XML in Android

Parse XML in Android

Get the full source code from here and don’t forget to comment on this post.

How to show a sliding window from below in Android?

Hello everyone,

I have already showed you how to use a SlidingViewer to create a slidingWindow. Today I will show another way to create such a window with the help of animation.

First Create a file named “SlidingPanel.java” and copy this code into it.

package com.pack.coderzheaven;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class SlidingPanel extends LinearLayout
{
	private Paint	innerPaint, borderPaint ;

	public SlidingPanel(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public SlidingPanel(Context context) {
		super(context);
		init();
	}

	private void init() {
		innerPaint = new Paint();
		innerPaint.setARGB(100, 25, 25, 75); //gray
		innerPaint.setAntiAlias(true);

		borderPaint = new Paint();
		borderPaint.setARGB(255, 255, 255, 255);
		borderPaint.setAntiAlias(true);
		borderPaint.setStyle(Style.STROKE);
		borderPaint.setStrokeWidth(5);
	}

	public void setInnerPaint(Paint innerPaint) {
		this.innerPaint = innerPaint;
	}

	public void setBorderPaint(Paint borderPaint) {
		this.borderPaint = borderPaint;
	}

    @Override
    protected void dispatchDraw(Canvas canvas) {

    	RectF drawRect = new RectF();
    	drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight());

    	canvas.drawRoundRect(drawRect, 5, 5, innerPaint);
		canvas.drawRoundRect(drawRect, 5, 5, borderPaint);

		super.dispatchDraw(canvas);
    }
}

This is the layout for the Panel window that comes up. Actually this java file creates gradiant only. No visual components are created with this code.

Now the main.xml, the place where “SlidingPanel ” is used.
Copy this code to your main.xml file

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

    <ImageButton
    		android:id="@+id/show_popup_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_gravity="left"
			android:background="@drawable/open"
	        />

	<com.pack.coderzheaven.SlidingPanel
			android:id="@+id/popup_window"
    	    android:layout_width="fill_parent"
        	android:layout_height="wrap_content"
        	android:orientation="vertical"
        	android:gravity="left"
        	android:padding="1px"
        	android:background="@drawable/white">

		<LinearLayout	xmlns:android="http://schemas.android.com/apk/res/android"
					    android:orientation="horizontal"
					    android:layout_width="fill_parent"
					    android:layout_height="fill_parent"
					    android:background="@drawable/gradient_bar">

			<TextView
					android:id="@+id/site_name"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
	        		android:textStyle="bold"
	        		android:textSize="16px"
	        		android:text="CoderzHeaven"
	        		android:layout_gravity="center"
	        		android:layout_alignParentLeft="true"
	        		android:textColor="@drawable/black"
	        		android:layout_weight="1"
	        		android:layout_marginLeft="5px"/>

			<ImageButton android:id="@+id/hide_popup_button"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
	    			android:layout_alignParentRight="true"
			        android:layout_centerInParent="true"
	    			android:layout_margin="2px"
	    			android:layout_gravity="center"
			        android:background="@drawable/close"/>

		</LinearLayout>

	    <TextView	android:id="@+id/site_description"
			        android:layout_width="wrap_content"
			        android:layout_height="wrap_content"
				android:textColor="@drawable/black"
				android:textStyle="italic"
	        		android:layout_margin="5px"/>

	</com.pack.coderzheaven.SlidingPanel>

</LinearLayout>

Make sure you have all the resources(images) for the xml.

Now create a folder named “anim” inside “res” folder and create an xml named “popup_hide.xml” and another one named “popup_show.xml”
popup_hide.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="750"/>
</set>

popup_show.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="750"/>
</set>

These two files create the animation for the window.

Now create file named gradient_bar.xml in the “res/drawable” folder and copy this code into it.
This is applied as background for the title in the sliding window.
You can edit the animation files to change the duration of the window coming.

Now the main java file
The file is named “PopUpAnimationDemo.java

package com.pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.TextView;

public class PopUpAnimationDemo extends Activity {

	private Animation animShow, animHide;

	@Override
	public void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        setContentView(R.layout.main);
        initPopup();
    }

    private void initPopup() {

    	final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);

    	// Hide the popup initially.....
    	popup.setVisibility(View.GONE);

    	animShow = AnimationUtils.loadAnimation( this, R.anim.popup_show);
    	animHide = AnimationUtils.loadAnimation( this, R.anim.popup_hide);

    	final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
    	final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
    	showButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.setVisibility(View.VISIBLE);
				popup.startAnimation( animShow );
				showButton.setEnabled(false);
				hideButton.setEnabled(true);
        }});

        hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.startAnimation( animHide );
				showButton.setEnabled(true);
				hideButton.setEnabled(false);
				popup.setVisibility(View.GONE);
        }});

    	final TextView locationName = (TextView) findViewById(R.id.site_name);
        final TextView locationDescription = (TextView) findViewById(R.id.site_description);

        locationName.setText("CoderzHeaven");
        locationDescription.setText("Heaven of all working codes"
        							+ " A place where you can ask, share & even shout for code! Let’s share a wide range of technology here." +
        	  						" From this site you will get a lot of working examples in your favorite programming languages!." +
        	  						" Always remember we are only one comment away from you… Let’s shorten the distance between your doubts and your answers…");

	}
}

Here is the Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Sliding Window Demo</string>
</resources>

Now create a file named colors.xml in the res/values folder and copy this into it

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <string name="select_Category">Select Category</string>
	<drawable name="white">#ffffff</drawable>
	<drawable name="black">#000000</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
	<drawable name="darkgrey">#606060</drawable>
</resources>

Click on the ImagButton to open the sliding Window

Sliding Window

Sliding Window

Sliding Window

Sliding Window

Download the whole project from here

Please don’t forget to add your valuable comments on this post, because comments are our encouragements for future posts.

How to start with Google Maps in Android?

Hello everyone, in this tutorial I will show you how to start with Google Maps in android.

Android Google Maps

Android Google Maps

Follow these steps while connecting to Google Maps in android.
Create a project with “Google APIs” as the Base SDK.

First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of “C:Documents and SettingsLocal SettingsApplication DataAndroid”. The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.

For simplicity, copy this file (debug.keystore) to a folder in C: (for example, create a folder called “C:Android”).

Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the “C:Program FilesJavabin” folder.

Issue the following command.

keytool.exe -list -alias androiddebugkey -keystore “C:androiddebug.keystore” -storepass android -keypass android

If you have added the path in the environment variables then you can execute this command from anywhere on the command line.

After that you will get a key, copy that key and go to http://code.google.com/android/maps-api-signup.html

Paste your code there and get the “Google Maps API key”

Now go to the main.xml file in your project and do as follows.

<?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">
<view android:id="@+id/mv"
    class="com.google.android.maps.MapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:clickable="true"
    android:apiKey="your_api_key goes here"
 />
</LinearLayout>

Now you are done save this file and load this xml file as layout in the java file.
Make sure you have internet connection in the emulator otherwise the map will not load.

This is the java file

package pack.coderzheaven;

import android.os.Bundle;
import com.google.android.maps.MapActivity;

public class MapDemo extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}

At last the Most important things to do in the AndroidManifest file
Add necessary permissions like INTERNET etc and include this library

inside the application tag.

My Manifest will look like this

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".MapDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="com.google.android.maps" />

    </application>

     <uses-sdk android:minSdkVersion="6" />
</manifest>

Now you are done go on and run the application

You can download the complete source code of the project here

How to remove a view in your xml layout file using program?

Hello everyone,
this is a simple example showing how to remove a view in android that is created using your xml file.

This is the xml file that contains a TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="CoderzHeaven"
    android:id="@+id/tv"
    />
</LinearLayout>

Here is the java code for removing this view

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class RemoveViewDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        View tv= (View)findViewById(R.id.tv);
        ((LinearLayout)tv.getParent()).removeView(tv);
    }
}

After running this program you will not see the TextView that was in your layout file.
Please leave your valuable comments on this post.

How to create a splash screen in android?

Hello everyone today i will show you how to create a splash screen in android.
This is one of the simplest ways to create a splash screen however there are another ways to create the splash screen.
Lets look at the code.

We need two layouts one for the splash screen and another for the first screen that comes after splash screen.

The splash screen layout will look like this.
splashscreen.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">
    <ImageView android:src="@drawable/android"
    android:layout_width="fill_parent"
     android:id="@+id/imageView1"
     android:layout_height="fill_parent"></ImageView>
</LinearLayout>

Now the main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Splash screen Demo from CoderzHeaven"
    />
</LinearLayout>

Now the main java file.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;

public class SplashScreenDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
        creatingSplashScreen();
    }

	private void createFirstScreen()
	{
	    	   setContentView(R.layout.main);
	}

	private void creatingSplashScreen()
	{
		 new CountDownTimer(5000, 1000) {
                   public void onTick(long millisUntilFinished)
		     {
		     }

		     public void onFinish() {
		    	 createFirstScreen();
		     }
		  }.start();
	}
}

Make sure you have an image named “android.png” or “android.jpg” in your res/drawable folder.

Merge two layout xml in android

Merging layout is an excellent feature in android. Separate xml can be included in a single xml.

For this first i create a main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

 <TextView
	android:text="Account"
	android:id="@+id/account"
	android:layout_below="@+id/title"
	 android:padding="10dip"
	android:layout_alignParentLeft="true"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	>
</TextView>
<EditText
	android:id="@+id/youtube_feed_TF"
	android:hint="Username"
	android:layout_marginLeft="10dip"
	android:inputType="textEmailAddress"
	android:layout_below="@+id/account"
	android:layout_centerHorizontal="true"
	android:layout_width="fill_parent"
	android:padding="10dip"
	android:layout_height="wrap_content"
></EditText>
<include layout="@layout/footer2button"/>

</RelativeLayout>

In the bottom you can see that i have included a xml file named footer2button.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
	android:layout_width="fill_parent"
	android:gravity="bottom"
	android:id="@+id/bottomlayout"
	android:layout_height="wrap_content"
	android:layout_alignParentBottom="true">

			<Button android:layout_height="wrap_content"
				 android:id="@+id/backbutton"
				 android:text="Back"
				 android:layout_width="wrap_content"
				 android:layout_weight="1"
				 android:layout_alignParentBottom="true">
			</Button>

			<Button android:layout_height="wrap_content"
				android:id="@+id/nextbutton"
				 android:text="Next"
				 android:layout_width="wrap_content"
				 android:layout_weight="1"
				 android:layout_alignParentBottom="true">
		   </Button>

</LinearLayout>
</merge>

The Merged layout will be like this

How to Open camera in ANDROID?

Hello everyone..
In today’s tutorial I will show you how to use camera in ANDROID in your program.
In this tutorial we will be having a button which will open the camera and after taking the photo it will show it in an imageView.

Note: This program will work only in the real device not in the emulator. So make sure to test it in the device itself. Also make sure to add the permission while using camera as shown below in your AndroidManifest file.

 <uses-feature android:name="android.hardware.camera"></uses-feature>  

Here is the main java file code

package com.coderzheaven;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class OpenCameraDemo extends Activity {

	private static final int CAMERA_PIC_REQUEST = 2500;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				 startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
			}
		});
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_PIC_REQUEST) {
        	  Bitmap image = (Bitmap) data.getExtras().get("data");
              ImageView imageview = (ImageView) findViewById(R.id.ImageView01);
              imageview.setImageBitmap(image);
        }
    }
}

Now the main.xml file which contains the button and the imageview.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<ImageView
	android:id="@+id/ImageView01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</ImageView>
<Button
	android:text="Open Camera"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

The strings.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, OpenCameraDemo!</string>
    <string name="app_name">OpenCamera</string>
</resources>

And the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

      <uses-feature android:name="android.hardware.camera"></uses-feature>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".OpenCameraDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Please leave your valuable comments on this post.

How to use SeekBar in ANDROID?

Here is a simple example to show how to use seek Bar in android.

Create a new project and place this code in it.

package com.coderzheaven;

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

public class SeekBarDemo extends Activity  implements SeekBar.OnSeekBarChangeListener {
    SeekBar mSeekBar;
    TextView mProgressText;
    TextView mTrackingText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        mSeekBar = (SeekBar)findViewById(R.id.seek);
        mSeekBar.setOnSeekBarChangeListener(this);
        mProgressText = (TextView)findViewById(R.id.progress);
        mTrackingText = (TextView)findViewById(R.id.tracking);
    }

    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
        mProgressText.setText(progress + " " +
                getString(R.string.seekbar_from_touch) + "=" + fromTouch);
    }

    public void onStartTrackingTouch(SeekBar seekBar) {
        mTrackingText.setText(getString(R.string.seekbar_tracking_on));
    }

    public void onStopTrackingTouch(SeekBar seekBar) {
        mTrackingText.setText(getString(R.string.seekbar_tracking_off));
    }
}

The main.xml file

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

    <SeekBar android:id="@+id/seek"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"
        android:secondaryProgress="75" />

    <TextView android:id="@+id/progress"
       	android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView android:id="@+id/tracking"
       	android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

The strings.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SeekBarDemo</string>
    <string name="seekbar_tracking_on">Tracking on</string>
    <string name="seekbar_tracking_off">Tracking off</string>
    <string name="seekbar_from_touch">from touch</string>
</resources>
SeekBar Demo in ANDROID

SeekBar Demo in ANDROID

Here is another example to show How to get the current progress on your SeekBar in android?

Please leave your valuable cmments

Simple View Animation in ANDROID?

Hi all…..
In this post I will show you a simple animation using a textView.
It’s really simple.

Steps.

1. Create a fresh project and copy this java code into it.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Toast;

public class AnimationDemo extends Activity implements AnimationListener {

	View v;
	Boolean STOP = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void startAnimation(View view) {
		Animation animation = AnimationUtils.loadAnimation(this,R.anim.animation);
		animation.setAnimationListener(this);
		View animatedView = findViewById(R.id.textview);
		animatedView.startAnimation(animation);
	}

    public void stopAnimation(View view){
    	Toast.makeText(this, "Animation will stop after this loop.", Toast.LENGTH_SHORT).show();
    	STOP = true;
    }
	@Override
	public void onAnimationStart(Animation animation) {
		Toast.makeText(this, "Animation started", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
		if(STOP == false)
			startAnimation(v);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
	}
}

2. Create a folder named “anim” inside the res folder and create a file named “animation.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
	android:shareInterpolator="true">
	<rotate android:fromDegrees="0" android:toDegrees="360"
		android:duration="10000" android:pivotX="50%" android:pivotY="50%"
		android:startOffset="10">
	</rotate>
</set>

3. copy this code to your “main.xml” file

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

	<button
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Start Animation"
		android:onClick="startAnimation">
	</button>

	<button
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Stop Animation"
		android:onClick="stopAnimation">
	</button>

	<textView
		android:id="@+id/textview"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello" />

</linearLayout>

4. Clean your project and run it.

Click the start animation button will start the animation and stop button will stop the animation after one loop.
The code is self explanatory, so I am not going to explain the code.

ANDROID Animation example

ANDROID Animation example

Join the Forum discussion on this post

Customizing your button or TextView or another view in ANDROID.

Beautifying our applications is one of the main features of your application’s success.
In ANDROID there are many possible ways to do this.
For eg. We need to have different colors for our buttons, However we can give backgrounds for buttons and all. But we can do many by using our custom xml files, like changing colors on button press and release, transitions etc. This tutorial explains such an example. Extend this example to create your own custom button.

Create a fresh project and copy this code to your main file.

package pack.coderzheaven;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class SelectorExample extends Activity {
    private Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Button clicked!!");
			}
		});

        ImageButton button = (ImageButton) findViewById(R.id.button);
        TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
        drawable.startTransition(5000);

        Resources res = getResources();
        Drawable shape = res. getDrawable(R.drawable.gradient_box);

        TextView tv = (TextView)findViewById(R.id.textview);
        tv.setBackgroundDrawable(shape);
    }
}

Now the main.xml file

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

	<ImageButton android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:src="@drawable/transition">
	</ImageButton>

	<TextView
		android:id="@+id/textview"
		android:text="CoderzHeaven"
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	<Button android:id="@+id/Button01"
		android:background="@drawable/buttonhighlight"
		android:layout_height="50px"
		android:layout_width="fill_parent"
		android:text="CoderzHeaven"	>
	</Button>
</LinearLayout>

Now create an xml file named “gradient_box.xml” in your drawable folder and copy this code to it.
This xml helps you to define the shape for the view for which you are applying this.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Now create an xml file named “transition.xml” in your drawable folder and copy this code to it.
This xml file is for applying a transition for your view

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/on" />
    <item android:drawable="@drawable/off" />
</transition>

Now the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.selectors"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SelectorExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Note: Make sure that you have all the images in your drawable folder as shown in the image below.

See the ImageButton transformation in the consequent pictures.


Please leave your comments if you find this post useful!

How to check SDCard free space in ANDROID?

This is a simple example that shows how many bytes are free in your SDCard.
Inorder to run this example, you have to create an SDCard and start the emulator with the SDCard.

Now create a fresh project and name it “FreeSpaceActivity.java” and copy the following code to it.

package pack.coderzheaven.check_space;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.widget.TextView;

public class FreeSpaceActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double avail_sd_space = (double)stat_fs.getAvailableBlocks() *(double)stat_fs.getBlockSize();
        double GB_Available = (avail_sd_space / 1073741824);
        System.out.println("Available GB : " + GB_Available);

        TextView tv = (TextView)findViewById(R.id.tv);
        tv.setText("Your SD Card is " + GB_Available + " bytes free." );
        tv.setTextColor(Color.GREEN);
        tv.setTextSize(20);
    }
}

The main.xml file

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

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven.check_space"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FreeSpaceActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Please leave your comments if the post was useful.

Free space in SD Card

Free Space in SD Card

Applying a shape to xml in android

By adding a custom shape we can make the layout more attractive.
For this we have to create a xml file and specify this in the main layout xml file

First make a xml inside the drawable folder.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
	<solid android:color="#F2F2F2"/>
    <stroke android:width="1dp" android:color="#000000" />
    <corners android:radius="5dp" />
</shape>

Then in the main file specify this shape like this. The “category” is the name of the xml specifying the shape

android:background="@drawable/category"

Now i gives you the whole xml file

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

  <TableLayout
  	android:layout_width="fill_parent"
  	android:stretchColumns="1"
  	android:layout_weight="1"
  	android:padding="5dip"
  	android:background="@drawable/categorybackground"
 	android:layout_height="wrap_content" >
  	<TableRow>
  		<TextView android:text="App Name"
	  		android:id="@+id/textView1"
	  		android:layout_gravity="center_vertical"
	  		android:layout_width="fill_parent"
	  		android:layout_height="wrap_content"/>

  	</TableRow>
  	<View android:layout_width="fill_parent"
  			android:background="#000000"
	  		android:layout_height="1dip"/>
  	<TableRow>
  		<TextView android:text="Icon Label"
	  		android:id="@+id/textView1"
	  		android:layout_gravity="center_vertical"
	  		android:layout_width="fill_parent"
	  		android:layout_height="wrap_content"/>

  	</TableRow>
  	<View android:layout_width="fill_parent"
  			android:background="#000000"
	  		android:layout_height="1dip"/>
  	<TableRow>
  		<TextView android:text="Category"
	  		android:id="@+id/textView1"
	  		android:layout_gravity="center_vertical"
	  		android:layout_width="fill_parent"
	  		android:layout_height="wrap_content"/>

  	</TableRow>
  	<View android:layout_width="fill_parent"
  			android:background="#000000"
	  		android:layout_height="1dip"/>
  	<TableRow>
  		<TextView android:text="Created By"
	  		android:id="@+id/textView1"
	  		android:layout_gravity="center_vertical"
	  		android:layout_width="fill_parent"
	  		android:layout_height="wrap_content"/>

  	</TableRow>
  	<View android:layout_width="fill_parent"
  			android:background="#000000"
	  		android:layout_height="1dip"/>
  	<TableRow>
  		<TextView android:text="Website"
	  		android:id="@+id/textView1"
	  		android:layout_gravity="center_vertical"
	  		android:layout_width="fill_parent"
	  		android:layout_height="wrap_content"/>

  	</TableRow>
    </TableLayout>
</RelativeLayout>

The layout look like this

Android phpMysql connection

First create a database  named “mydatabase” in MySql. Then create a table “tbl_user” with three fields (id, username and password).

The next step is to create a php page which will communicate between the  MySql database and the android application.

For this create a “Connections.php” page as shown below. It will set up a  connection to the database with the username and password

$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";

$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

Then the main PHP file is to be created. Actually the android application will call this php file along with the data(username and password ) and this code will check the database. If the details is valid then it will return “Y” and otherwise return “N”.

Here the data is passed as POST method. We can also use GET method where the data is passed along with the url . Android support both these two features.

<?php require_once('yourfolder/Connections.php'); mysql_select_db($database_localhost,$localhost);

$useremail = $_POST['UserEmail'];
$password = $_POST['Password'];

 $query_search = "select * from tbl_user where username = '".$useremail."' AND password = '".$password. "'";
 $query_exec = mysql_query($query_search) or die(mysql_error());
 $rows = mysql_num_rows($query_exec);

 if($rows --> 0) { echo "Y"; }
else  {echo "N"; }

So by now we created php and the database part. Then we have to focus on android section. For this first create a xml file which will be our login screen.The screen look like this.

The layout of the xml is displayed below.

<RelativeLayout
	  xmlns:android="http://schemas.android.com/apk/res/android"
	  android:layout_width="fill_parent"
	  android:layout_height="fill_parent"
	  android:background="#ff2a1703"
	  android:fadingEdge="horizontal">
	 <TextView
	 		android:id="@+id/text"
	 		android:text="manage your projects..."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:typeface="serif"
            android:textStyle="italic"
            android:layout_centerHorizontal="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="50dip"
            android:textSize="20sp" >
     </TextView>
	 <EditText
			android:id="@+id/username"
			android:layout_width="213dip"
			android:layout_marginTop="60dp"
			android:layout_below ="@+id/text"
			android:layout_centerHorizontal="true"
			android:layout_height="wrap_content"
			android:hint="username"
			android:gravity="center"
			android:textSize="18sp"
			android:typeface="sans"
			android:textStyle="italic">
	 </EditText>
	 <EditText
			android:id="@+id/password"
			android:layout_width="211px"
			android:layout_height="wrap_content"
			android:hint="password"
			android:textSize="18sp"
			android:typeface="sans"
			android:textStyle="italic"
			android:gravity="center"
			android:password="true"
			android:layout_marginTop="20dp"
			android:layout_below ="@+id/username"
			android:layout_centerHorizontal="true">
	 </EditText>
 	 <CheckBox
			android:id="@+id/check"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Remember me"
			android:layout_marginTop="10dp"
			android:layout_below ="@+id/password"
			android:layout_centerHorizontal="true">
	 </CheckBox>
	 <Button
			android:id="@+id/login"
			android:layout_width="141px"
			android:layout_height="wrap_content"
			android:text="Login"
			android:textSize="22sp"
			android:typeface="serif"
			android:textStyle="bold"
			android:layout_marginTop="20dp"
			android:layout_below ="@+id/check"
			android:layout_centerHorizontal="true">
	 </Button>
</RelativeLayout>

We now create the java file . This file should contain the 3 sections

1. Store the preference when the checkbox is checked
2. Establish a connection between this file and the php file
3. Validate the user

package com.ar.mydatabaseProject.pack;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class mydatabaseProject extends Activity
{
    /** Called when the activity is first created. */

	Button login;
	String name="",pass="";
	EditText username,password;
	TextView tv;
	byte[] data;
	HttpPost httppost;
	StringBuffer buffer;
	HttpResponse response;
	HttpClient httpclient;
	InputStream inputStream;
	SharedPreferences app_preferences ;
	List<NameValuePair> nameValuePairs;
	CheckBox check;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        check = (CheckBox) findViewById(R.id.check);

        String Str_user = app_preferences.getString("username","0" );
	    String Str_pass = app_preferences.getString("password", "0");
	    String Str_check = app_preferences.getString("checked", "no");
        if(Str_check.equals("yes"))
        {
        		username.setText(Str_user);
        		password.setText(Str_pass);
        		check.setChecked(true);
        }
        login.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v)
			{
				name = username.getText().toString();
				pass = password.getText().toString();
				String Str_check2 = app_preferences.getString("checked", "no");
				if(Str_check2.equals("yes"))
				{
					SharedPreferences.Editor editor = app_preferences.edit();
					editor.putString("username", name);
					editor.putString("password", pass);
					 editor.commit();
				}
				if(name.equals("") || pass.equals(""))
				{
					 Toast.makeText(mydatabaseProject.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
				}
				else
				{


			    try {
			    	httpclient = new DefaultHttpClient();
				    httppost = new HttpPost("http://10.0.2.2/android/user_validate.php");
			        // Add your data
			        nameValuePairs = new ArrayList<NameValuePair>(2);
			       nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
			        nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
			        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			        // Execute HTTP Post Request
			        response = httpclient.execute(httppost);
			        inputStream = response.getEntity().getContent();

			        data = new byte[256];

			        buffer = new StringBuffer();
	                int len = 0;
	                while (-1 != (len = inputStream.read(data)) )
	                {
	                    buffer.append(new String(data, 0, len));
	                }

	                inputStream.close();
			    }

			    catch (Exception e)
			    {
			    	Toast.makeText(mydatabaseProject.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
			    }
			    if(buffer.charAt(0)=='Y')
			    {
			    	Toast.makeText(mydatabaseProject.this, "login successfull", Toast.LENGTH_LONG).show();
			    }
			    else
			    {
			    	Toast.makeText(mydatabaseProject.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
			    }
				}
			}
		});
        check.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                // Perform action on clicks, depending on whether it's now checked
            	SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked())
                {


                	 editor.putString("checked", "yes");
                	 editor.commit();
                }
                else
                {
                	 editor.putString("checked", "no");
                	 editor.commit();
                }
            }
        });
    }
        public void Move_to_next()
        {

        //	startActivity(new Intent(this, zzz.class));
        }
}

At last don’t forget to put the permission in Manifest file

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


Note : if you have any problem in working with this post, please check this more simple version here.

Here is another more detailed explanation.

How to create Simple Login form using php in android? – Connect php with android.

Android listView with icons

In this post, we will have a list whose rows are made up of image, Here we just supply data to the adapter and helping the adapter to create a View objects for each row

The output will be

For this first create a xml file to hold the listview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
		<TextView
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:text="@string/hello"
	    />
	    <ListView
			android:id="@android:id/list"
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"/>

</LinearLayout>

The next objective is to create the xml for listview row. Here i create 2 components a imageview and a a textview for displaying the selected row. Also the image for the imageView is put in the drawable folder and is referred in this xml file.

<?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">
  <ImageView
		android:id="@+id/icon"
		android:layout_width="wrap_content"
		android:paddingLeft="4dip"
		android:paddingRight="4dip"
		android:layout_height="wrap_content"
		android:src="@drawable/icon"/>
	<TextView
		android:id="@+id/label"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textSize="24sp"/>
</LinearLayout>

ok. Next create one main java file. Here instead of activity we extend the class ListActivity.That is shown below

package com.ImageListView.pack;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ImageListView extends ListActivity
{
    /** Called when the activity is first created. */
	TextView selection;
	String[] names;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       names = new String[] { "sunday", "monday", "tuesday", "wednesday",
					"thrusday", "friday", "saturday",};

       this.setListAdapter(new ArrayAdapter<String>(this, R.layout.custom, R.id.label,names));
		selection=(TextView)findViewById(R.id.label);

	}

	public void onListItemClick(ListView parent, View v,int position,long id)
	{
	 	selection.setText(names[position]);
	}

}

The names array contains the elements that is to be displayed. The second parameter in the setlistAdapter is the name of the xml file we create for the row, the third is the imageView in the custom xml file and the last is the name of the array

Important
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen.

However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id “@android:id/list”

How to create a scrolling ListView in android?

ListView is like a tableView in iPhone or iOS . In this example i will show you how to add a String Array in to the ListView and also make the listView Scrollable.

First the xml file . Here the line

android:scrollbars=”vertical”

will make the scrolling vertically

<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
	<listView
			android:id="@+id/listview"
			android:scrollbars="vertical"
			android:layout_width="fill_parent"
			android:layout_height="200dip"
			android:layout_gravity="fill_vertical"
			android:layout_alignParentTop="true"
			>
		</listView>

</relativeLayout>

Now the java file

package com.Ch.Example.pack;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Example extends Activity
{
    /** Called when the activity is first created. */
	ListView list;
	private List<string> List_file;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);

        CreateListView();
    }
	private void CreateListView()
	{
		 List_file.add("Coderzheaven");
		 List_file.add("Google");
		 List_file.add("Android");
		 List_file.add("iPhone");
		 List_file.add("Apple");
		 //Create an adapter for the listView and add the ArrayList to the adapter.
		 list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
		 list.setOnItemClickListener(new OnItemClickListener()
		   {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//args2 is the listViews Selected index
				}
		   });
	}
}

The screen will be like this

Here is a other useful posts related to listviews.

1. ListView with Sections in android.
2. A Simple Layout with two listViews.

How to create custom layout for your spinner in ANDROID? or Customizable spinner

This code helps you to customize the spinner in ANDROID.

For that you have to create an XML file inside your layout folder as shown below and name it spinner.xml.
You can give all properties that are available for TextView inside this which is going to be then applied for your spinner.

<xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="14sp"
android:typeface="serif"
android:textStyle="bold|italic"
android:textColor="@drawable/yellow"
>
TextView>

Now I will show you how to add it to a spinner.

ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner,my_array);
My_spinner.setAdapter(my_Adapter);

“my_array” is an array that populates the spinner and “My_spinner” is the spinner.

Please leave your valuable comments if this post was useful…..

How to read and write an XML file in Adobe AIR or Flex?

AIR treats the XML files as just as normal file and so you can proceed using the FileStream classs. Please take a look at the sample code. Just copy and paste the following code to your main.MXML file and you are done.

  import flash.xml.XMLDocument;

  private function init():void
  {
   xmlTA.text = " Sample XML ";
   var fileStream:FileStream = new FileStream();
   var prefsXML:XML =
           Sample
           XML
        ;

   var file:File = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.open(file, FileMode.WRITE);

   var outputString:String = 'n';
   outputString += prefsXML.toXMLString();

   fileStream.writeUTFBytes(outputString);
   fileStream.close();

   /* Reading the XML File */
   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream.open(file, FileMode.READ);
   prefsXML= XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
   readTA.text = prefsXML;
   fileStream.close();

   /*
    The previous examples use FileStream objects opened for synchronous operation.
    You can also open files for asynchronous operations (which rely on event listener functions to respond to events).
    For example, the following code shows how to read an XML file asynchronously:
   */

   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.addEventListener(Event.COMPLETE, processXMLData);
   fileStream.openAsync(file, FileMode.READ);

   function processXMLData(event:Event):void
   {
       prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
       asyXML.text = prefsXML;
       fileStream.close();
   }

  }
 ]]>

Please post your comments on this post

Play Video using VideoView in ANDROID.

Playing a video file is simple in android. This post will help you.
Put your video in res/raw folder. If no raw folder present then create a new folder inside res.

package com.coderzheaven.pack;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class Example extends Activity {
    /** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState)
        {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
           showVideo();
       }
	private void showVideo()
	{
		VideoView vd = (VideoView)findViewById(R.id.videoview);
		Uri uri = Uri.parse("android.resource://package/"+R.raw.movie);
		MediaController mc = new MediaController(this);
		vd.setMediaController(mc);
		vd.setVideoURI(uri);
		vd.start();
	}
}

The main. xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
	<VideoView
			android:id="@+id/videoview"
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:layout_alignParentTop="true"
			>
		</VideoView>
</RelativeLayout>

Please leave your comments if this post was useful.