Image transition animation in Android

Hello all…

I have shown a lot of examples of animations in android.
Today I will show you how to show an image transition animation between two images. For that you have to create an xml named “expand_collapse.xml” inside the res/drawable folder.

The contents of “expand_collapse.xml” are

<transition xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/android_1" />
      <item android:drawable="@drawable/android_2" />
</transition>

Now in the main.xml place an imageView to show the transition

<?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"
    >
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toggle_image"
    />
</LinearLayout>

Now in the main java file I will show you how to apply this transition.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.widget.ImageView;

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

        Resources res = getApplicationContext().getResources();
        TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse);
        ImageView image = (ImageView) findViewById(R.id.toggle_image);
        image.setImageDrawable(transition);

        transition.startTransition(5000);
   }
}

How to create a custom layout for your camera in Android?

Hello everyone,

Today’s example shows how to create a custom layout for your camera preview, that is if you want a custom layout while your camera is opening.
This example helps you to achieve this.

First create a fresh project and name it CameraCustomLayout and copy this code to CameraCustomLayout.java file.

package com.coderzheaven.pack;

import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class CustomCameraActivity extends Activity implements SurfaceHolder.Callback {

	Camera camera;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	boolean previewing = false;
	LayoutInflater controlInflater = null;

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

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.custom, null);
        LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
        								   					LayoutParams.FILL_PARENT);
        this.addContentView(viewControl, layoutParamsControl);
    }

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if(previewing){
			camera.stopPreview();
			previewing = false;
		}

		if (camera != null){
			try {
				camera.setPreviewDisplay(surfaceHolder);
				camera.startPreview();
				previewing = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		camera.release();
		camera = null;
		previewing = false;
	}
}

After that create an xml file named custom.xml inside the res/layout folder and copy this code into it.
This is the layout which comes when you open the camera in your device.

<?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:gravity="left">

	<Button
		android:text="Click Me"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
	<Button
		android:text="Click Me too"
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>

Now in the main.xml file copy this code.
This file contains the SurfaceView which holds the cameraPreview.

<?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"
    >
<SurfaceView
	android:id="@+id/camerapreview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Now you are done.
Note : Please run it on a real device, because camera will not work on the emulator.

You can download the source code from here.
PLease dont forget to comment on this post if you like it.

How to install an APK into your device or emulator through command prompt or shell.

In this post I will show you how to install an apk on to the emulator or the device through the shell or command prompt.
Before experimenting with this post I assume that you have these done

1. Installed the Android SDK.
2. Added the adb path to the environment path.

This is how you add the path to the environment variable.

On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look for a line that sets the PATH environment variable and add the full path to your $SDK_ROOT/tools to it. If you don’t see a line setting the path, you can add one:

export PATH=${PATH}: On a Mac, look in your home directory for .bash_profile and proceed as for Linux. You can create the .bash_profile, if you haven’t already set one up on your machine.
On Windows, right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables, and add the full path to the tools/ directory under $SDK_ROOT to it.

Now In windows Go to command prompt and type

C: adb devices

if you have correctly set your path then your android devices will be listed here.

then copy your apk to the C: directory and issue this command

C:adb install your_apk.apk

Take a look at the screenshot. Here I am installing CreateTable.apk that is located in the C: directory.

Install the APK onto emulator.

Install the APK onto emulator or device

Show data in columns in a TableView dynamically in Android.

Hello all,
Often we need to show data from a source such as a database in a tableView like we see in an HTML Page.
Now in Android also we can do this with the help of TableLayout.
We can create dynamic rows and add data to it.
This is something that people in computer
classes
will benefit from knowing how to do this.

Here is the java code to implement this.
First create a java file named CreateTable.java and copy the contents into it.

package com.coderzheaven.pack;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class CreateTable extends Activity {

	 String companies[] = {"Google","Windows","iPhone","Nokia","Samsung",
			 			   "Google","Windows","iPhone","Nokia","Samsung",
			 			   "Google","Windows","iPhone","Nokia","Samsung"};
	 String os[] 	   =  {"Android","Mango","iOS","Symbian","Bada",
			 			   "Android","Mango","iOS","Symbian","Bada",
			 			   "Android","Mango","iOS","Symbian","Bada"};

	 TableLayout tl;
	 TableRow tr;
	 TextView companyTV,valueTV;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tl = (TableLayout) findViewById(R.id.maintable);
        addHeaders();
        addData();
    }

    /** This function add the headers to the table **/
    public void addHeaders(){

    	 /** Create a TableRow dynamically **/
        tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        /** Creating a TextView to add to the row **/
        TextView companyTV = new TextView(this);
        companyTV.setText("Companies");
        companyTV.setTextColor(Color.GRAY);
        companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        companyTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        companyTV.setPadding(5, 5, 5, 0);
        tr.addView(companyTV);	// Adding textView to tablerow.

        /** Creating another textview **/
        TextView valueTV = new TextView(this);
        valueTV.setText("Operating Systems");
        valueTV.setTextColor(Color.GRAY);
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        valueTV.setPadding(5, 5, 5, 0);
        valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        tr.addView(valueTV); // Adding textView to tablerow.

        // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        // we are adding two textviews for the divider because we have two columns
        tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        /** Creating another textview **/
        TextView divider = new TextView(this);
        divider.setText("-----------------");
        divider.setTextColor(Color.GREEN);
        divider.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        divider.setPadding(5, 0, 0, 0);
        divider.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        tr.addView(divider); // Adding textView to tablerow.

        TextView divider2 = new TextView(this);
        divider2.setText("-------------------------");
        divider2.setTextColor(Color.GREEN);
        divider2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        divider2.setPadding(5, 0, 0, 0);
        divider2.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        tr.addView(divider2); // Adding textView to tablerow.

        // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

    /** This function add the data to the table **/
    public void addData(){

    	for (int i = 0; i < companies.length; i++)
        {
            /** Create a TableRow dynamically **/
            tr = new TableRow(this);
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));

            /** Creating a TextView to add to the row **/
            companyTV = new TextView(this);
            companyTV.setText(companies[i]);
            companyTV.setTextColor(Color.RED);
            companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            companyTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            companyTV.setPadding(5, 5, 5, 5);
            tr.addView(companyTV);	// Adding textView to tablerow.

            /** Creating another textview **/
            valueTV = new TextView(this);
            valueTV.setText(os[i]);
            valueTV.setTextColor(Color.GREEN);
            valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            valueTV.setPadding(5, 5, 5, 5);
            valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            tr.addView(valueTV); // Adding textView to tablerow.

            // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
        }
    }
}

Here is the main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/LinearLayout01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	>
	<ScrollView
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:scrollbars="none">
		<TableLayout
		    android:layout_width="fill_parent"
		    android:layout_height="fill_parent"
		    android:stretchColumns="0,1"
		    android:id="@+id/maintable" >
		</TableLayout>
	</ScrollView>
</LinearLayout>

Now the Strings.xml file

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

Now the project is complete and you can see the result.

Creating tableRows dynamically in Android

Creating tableRows dynamically in Android

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.

Android 4.0 IceCream Sandwich Cool features

Android 4.0 is here and it is completely different from its predecessors.
The rate at which android is growing is unbeleivable.
Students earning computer forensics
degrees
need to be aware of all different systems, so they should learn
about these features.
These are some of the features.

1. Refined, evolved UI

2. Home screen folders and favorites tray

3. Resizable widgets

4. New lock screen actions

5. People and profiles

Take a look at the Features here

Parsing XML in Android a simple example

This is a simple example showing how to parse an xml in Androi.
In this method the xml file is stored in res/xml folder.

First create a folder named “xml” inside the raw folder.
Then create an xml file named test.xml and copy the contents into it.

<?xml version="1.0" encoding="utf-8"?>
<root>
<name>
CoderzHeaven
</name>
<blog>
 Google
 <sub2>Android</sub2>
</blog>
</root>

This is the XML file we are going to parse.


Now the main.xml file. We place a textView to view the contents of the parsing.

<?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 XML Parsing Demo"
  android:textColor="#FF0000"
  android:textStyle="bold|italic"
  android:textSize="14sp"
  android:layout_margin="10dp"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/xml_tv"
  android:layout_margin="10dp"
  />
</LinearLayout>

Now the main java file that does the parsing.
We use the “XmlPullParser” class to parse the XML

package com.coderzheaven;

import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

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

	      TextView myXmlContent = (TextView)findViewById(R.id.xml_tv);
	      String stringXmlContent;

		  stringXmlContent = getAllXML();
		  myXmlContent.setText(stringXmlContent);

	  }

	  public String getAllXML(){

		  Activity activity = this;
		  String str = "";

		  Resources res = activity.getResources();
		  XmlResourceParser xpp = res.getXml(R.xml.test);

		  try {
				xpp.next();
				int eventType = xpp.getEventType();
				System.out.println("eventType : " + eventType);
				while (eventType != XmlPullParser.END_DOCUMENT)
			    {
					 if(eventType == XmlPullParser.START_DOCUMENT){
						 str += "nXML Parsing Starting...n";
					 }
					 else if(eventType == XmlPullParser.START_TAG)
				     {
						 str +=  "nroot tag: "+xpp.getName();
				     }
				     else if(eventType == XmlPullParser.END_TAG)
				     {
				    	 str += "nending tag: "+xpp.getName();
				     }
				     else if(eventType == XmlPullParser.TEXT)
				     {
				    	 str += "nvalue : "+xpp.getText();
				     }
				     eventType = xpp.next();
			    }
				 str += "nnXML parsing Ending......";

		  } catch (XmlPullParserException e) {
				e.printStackTrace();
		  } catch (IOException e) {
				e.printStackTrace();
		  }
		  return str;
	  }

	}

That’s all parsing is complete Go on and run the program.

Parsing XML in Android

Parsing XML in Android


Other types of XML Parsing will be covered in the following posts please be in touch

Download the fullsource from here

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 add markers on our desired location in Google Maps Android?

In the last few posts I have showed some examples of how to work with Google maps.
In this post I will show you how to add a marker in our desired position in the map.

Adding something on top of a map is called overlay.
Here we will create a class to add an overlay.

This code helps to add the overlay

 MapOverlay mapOverlay = new MapOverlay();
 List<Overlay> listOfOverlays = map_view.getOverlays();
 listOfOverlays.clear();
 listOfOverlays.add(mapOverlay);

Refer the previous posts for other resources and only change the java code as given below and also add a resource arrow.png to the res/drawable folder.
That is it.
Here is the modified java code.

package pack.coderzheaven;

import java.util.List;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MapDemo extends MapActivity {

	MapView map_view;
	MapController mc;
	GeoPoint p;

    @Override
    public void onCreate(Bundle savedInstanceState) {

    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        map_view = (MapView)findViewById(R.id.mv);
        map_view.setBuiltInZoomControls(true);    // Show the Zoom Controls
        //map_view.setSatellite(true);
        /** You can also display the map in street view, using the setStreetView() method: **/
        //map_view.setStreetView(true);

        mc = map_view.getController();
        String coordinates[] = {"28.38", "77.12"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint(
            (int) (lat * 1E6),
            (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(10);

        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = map_view.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);

        map_view.invalidate();

    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        MapController mc = map_view.getController();
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_1:
                mc.zoomIn();
                break;
            case KeyEvent.KEYCODE_2:
                mc.zoomOut();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

	// This is the overlay that we add above the map.....
	 class MapOverlay extends com.google.android.maps.Overlay
	    {
	        @Override
	        public boolean draw(Canvas canvas, MapView mapView,
	        boolean shadow, long when)
	        {
	            super.draw(canvas, mapView, shadow);

	            //---translate the GeoPoint to screen pixels---
	            Point screenPts = new Point();
	            mapView.getProjection().toPixels(p, screenPts);

	            //---add the marker---
	            Bitmap bmp = BitmapFactory.decodeResource(
	                getResources(), R.drawable.arrow);
	            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
	            return true;
	        }
	    }
}
markers in Google Maps

Adding markers to google Maps in Android

Please leave your valuable comments if you found this post useful.

Please wait for the next post on how to add a custom overlay with our own layout and getting the touch location on the map.
Complete source code of all google Maps examples will be available for download in the coming posts.

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

Showing a desired location on Google Maps in Android?

In the previous post I showed you how to start with google Maps and changing the views and changing the zooming of maps.
Today I will show how to show our desired location in the Map.
For that we need the latitude and longitude of the location we want to show the location on the map.

The only change is in the java code of the previous post.
here is the Modified code

package pack.coderzheaven;

import android.os.Bundle;
import android.view.KeyEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MapDemo extends MapActivity {

	MapView map_view;
	MapController mc;
	GeoPoint p;

    @Override
    public void onCreate(Bundle savedInstanceState) {

    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        map_view = (MapView)findViewById(R.id.mv);
        map_view.setBuiltInZoomControls(true);    // Show the Zoom Controls
        //map_view.setSatellite(true);
        /** You can also display the map in street view, using the setStreetView() method: **/
        //map_view.setStreetView(true);

        mc = map_view.getController();
        String coordinates[] = {"28.38", "77.12"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint(
            (int) (lat * 1E6),
            (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(10);
        map_view.invalidate();

    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        MapController mc = map_view.getController();
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_1:
                mc.zoomIn();
                break;
            case KeyEvent.KEYCODE_2:
                mc.zoomOut();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Note : Replace the API key with yours in the XML as I have mentioned in the previous post.

Showing a location on Google Maps

Showing a location on Google Maps

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

Displaying Zoom Controls and Changing the View of Google Maps in Android. or Create ZoomIn or Out by Code

Hello all………

In the previous post I showed you how to start with Google maps in android.
In this post I will show you how to show zooming controls and changing the view of the map.

Actually this is really simple.

Add these lines to the previous code to add the zooming controls.

map_view.setBuiltInZoomControls(true);    // Show the Zoom Controls

Now how to change the view of the map. To change it to satellite View apply this code.

map_view.setSatellite(true);

To change the view to StreetView apply this code

map_view.setStreetView(true);

After applying this the screen will appear like this

Adding Zoom controls

Adding Zoom controls

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

Using Asynchronous task in Android

Hello all,

Today I will show you a demo on how to use Asynchronous task in android. You should use this if you are doing a task that takes longer time to complete.
This class doesnot block the UI thread so the “Application Not Responding” dialog will not appear when you are doing a big task.
You should subclass the Asynchronous class to use it and pass to this function “doInBackground” the parameters.
You can access the UIThread in the “onPostExecute” method.
Please check this example.
Here is 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"
    >

<Button
	android:layout_height="wrap_content"
	android:layout_width="fill_parent"
	android:id="@+id/readWebpage"
	android:onClick="readWebpage"
	android:text="Load Webpage">
</Button>
<TextView
	android:id="@+id/TextView01"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:text="Asynchronous task Demo from CoderzHeaven">
</TextView>
</LinearLayout>

Here is the AndroidManifest.xml file
Make sure to add the android.permission.INTERNET permission in this file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AsynsTaskExample"
                  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>

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

The main java file

package com.pack.coderzheaven;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AsynsTaskExample extends Activity {
	private TextView textView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textView = (TextView) findViewById(R.id.TextView01);
	}

	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = "";
			for (String url : urls) {
				DefaultHttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);
				try {
					HttpResponse execute = client.execute(httpGet);
					InputStream content = execute.getEntity().getContent();

					BufferedReader buffer = new BufferedReader(
							new InputStreamReader(content));
					String s = "";
					while ((s = buffer.readLine()) != null) {
						response += s;
					}

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),"Some Error Occurred! " + e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			textView.setText(result);
			Toast.makeText(getApplicationContext(),"Loading WebPage Complete", Toast.LENGTH_LONG).show();
		}
	}

	public void readWebpage(View view) {
		DownloadWebPageTask task = new DownloadWebPageTask();
		task.execute(new String[] { "http://www.google.com" });

	}
}

Flitering a ListView using an input from an EditText in Android.

Hello everyone

In today’s tutorial I will show you how to filter a ListView based on an input from the EditText.
This is really simple we just need to call getFilter().filter(search_string) on the adapter to filter the values from the ListViews.
Just take a look at this example.

Here is the layout file 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">
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/filterText">
        <requestFocus></requestFocus>
    </EditText>
    <ListView android:layout_height="wrap_content" android:id="@+id/android:list"
        android:layout_width="fill_parent"></ListView>
</LinearLayout>

Here is the java file named FilterListViewsDemo.java

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class FilterListViewsDemo extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                getModel());
        setListAdapter(adapter);
        EditText filterEditText = (EditText) findViewById(R.id.filterText);
        filterEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                adapter.getFilter().filter(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private List<String> getModel() {
        List<String> list = new ArrayList<String>();
        list.add("Android");
        list.add("Windows7");
        list.add("iPhone");
        list.add("RIM");
        list.add("Symbian");
        list.add("Bada");
        list.add("MacOSX");
        list.add("WindowsXP");
        list.add("CoderzHeaven");
        return list;
    }
}

You can download the full source code from here

Most Common and most important String functions in Corona.

Here are some of the string functions that are most commonly used in Corona SDK.
In this example you can find all the common string functions with a wroking example for each.
This example contains functions to

1. Check the first character in a string
2. Check the last character in a string.
3. Changing the first character in a string to uppercase.
4. Toggling the case.
5. Splitting a string.
6. Email validation.
7. Getting the character from it’s ASCII value.
8. Finding a pattern in a string.
9. Splitting a sentence into words.
10. Changing to lowercase, uppercase and reversing a string.


print ("String functions in Corona");

-- Function to check whether the first character is the given character. --
function startWith(String, search_char)
	return(string.sub(String,1,string.len(search_char)) == search_char);
end

-- Function to check whether the last character is the given character. --
function endsWith(String, search_char)
	return(string.sub(String,-string.len(search_char)) == search_char);
end

--Function to change the first character of a string to upper case --
function changeFirstCharToUpperCase(String)
	return String:gsub("^%l", string.upper)
end

function ToggleCase(String)
	return string.gsub (String, "%f[%a]%u+%f[%A]", string.lower)
end

-- Iterating through words in a string.
function getWords(String)
	local i = 1;
	for word in String:gmatch("%w+") do
		print("word "..i.." : "..word);
		i = i+ 1;
	end
end

local str = "CoderzHeaven";
local search_first_char = "C";
local search_end_char = "n"

if(startWith(str,search_first_char)) then
    print("startWith : "..search_first_char);
else
	print ("Doesnot start with "..search_first_char);
end

if(endsWith(str,search_end_char)) then
    print("endsWith : "..search_end_char);
else
	print ("Doesnot end with "..search_end_char);
end

str = "coderzHeaven";
print ("changeFirstCharToUpperCase : "..changeFirstCharToUpperCase(str))

str = "CoderzHeaven Heaven of all working codes";
print("ToggleCase : "..ToggleCase(str));

getWords(str);

--- Check whether this is a correct format of email address....
email="[email protected]"
if (email:match("[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?")) then
  print(email .. " is a valid email address")
else
	print('Invalid email address')
end

-- Get the charater from it's ASCII Value.....
print('ASCII Value of char : '..string.char (65))

--Looks for the first match of pattern in the string s.
--If it finds a match, then find returns the indices of s
--where this occurrence starts and ends; otherwise, it returns nil.
print(string.find (str, 'der',2,false ));

--Returns a formatted version of its variable number of arguments following
--the description given in its first argument (which must be a string)
print( string.format('%q', 'a string with "quotes" and n new line'));

local s = "hello world from CoderzHeaven"
 for w in string.gmatch(s, "%a+") do
   print(w)
 end

 --Find String Length
 print("length : "..string.len(s));

 -- Change to Lowercase
 print(string.lower (s));

 --Reverse a string
 print(string.reverse (s));

 --Change to Uppercase.....
 print(string.upper (s))

Different ways to trim a string in Corona SDK.

Here are the different ways to trim a string in Corona SDK.


-- CoderzHeaven String Trimming examples in Corona.
-- Here you can see different methods for trimming a string in corona.

function trim1(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end

function trim2(s)
  return s:match "^%s*(.-)%s*$"
end

function trim3(s)
  return s:gsub("^%s+", ""):gsub("%s+$", "")
end

function trim4(s)
  return s:match"^%s*(.*)":match"(.-)%s*$"
end

function trim5(s)
  return s:match'^%s*(.*%S)' or ''
end

-- has bad performance.. use at your own risk.
function trim6(s)
  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

local str = " CoderzHeaven ";
print("--------------Trimming a string in Corona SDK---------------");
print ('Str Original Length Length : '..string.len(str))

str = trim1(str);
print ('Str Length using First Function  : '..string.len(str))

-- reassigning to check trim function using other functions.
str = " CoderzHeaven ";
str = trim2(str);
print ('Str Length using second function : '..string.len(str))

str = " CoderzHeaven ";
str = trim3(str);
print ('Str Length using third function  : '..string.len(str))

Please check the console for the output.

Download the source code from here

Custom Tabs in Android

This is a sample tutorial for creating custom tabs that look like android tabs may be beautiful than that with buttons and styles.
Here is the sample code for that.

package pack.coderzheaven;

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

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

This is the layout for the tabs

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
	android:id="@+id/bottom_tab_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    android:background="@drawable/black_gradiant"
    >
 <Button
  	android:layout_height="wrap_content"
  	android:id="@+id/home"
  	android:text="Home"
  	android:layout_width="fill_parent"
  	android:textStyle="bold"
  	android:textSize="8sp"
  	android:layout_weight="1"
  	android:textColor="@drawable/black"
  	android:drawableTop="@drawable/home"
  	android:background="@drawable/custom_gradiant"
  	android:padding="2dp"
  	android:layout_marginRight="2dp"
  	android:gravity="center|bottom">
  </Button>

   <Button
  	android:layout_height="wrap_content"
  	android:id="@+id/media"
  	android:text="Video"
  	android:layout_width="fill_parent"
  	android:textStyle="bold"
  	android:textSize="8sp"
  	android:layout_weight="1"
  	android:textColor="@drawable/black"
  	android:drawableTop="@drawable/video"
  	android:background="@drawable/custom_gradiant"
  	android:padding="2dp"
  	android:layout_marginRight="2dp"
  	android:gravity="center|bottom">
  </Button>

   <Button
  	android:layout_height="wrap_content"
  	android:id="@+id/news_letter"
  	android:text="Audio"
  	android:layout_width="fill_parent"
  	android:textStyle="bold"
  	android:textSize="8sp"
  	android:layout_weight="1"
  	android:textColor="@drawable/black"
  	android:drawableTop="@drawable/audio"
  	android:background="@drawable/custom_gradiant"
  	android:padding="2dp"
  	android:layout_marginRight="2dp"
  	android:gravity="center|bottom">
  </Button>

   <Button
  	android:layout_height="wrap_content"
  	android:id="@+id/news_letter"
  	android:text="Mail"
  	android:layout_width="fill_parent"
  	android:textStyle="bold"
  	android:textSize="8sp"
  	android:layout_weight="1"
  	android:textColor="@drawable/black"
  	android:drawableTop="@drawable/email"
  	android:background="@drawable/custom_gradiant"
  	android:padding="2dp"
  	android:gravity="center|bottom">
  </Button>
</LinearLayout>
</merge>

The main.xml file that includes the tab layout.

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

   <Button
  	android:layout_height="wrap_content"
  	android:id="@+id/home"
  	android:text="Custom Android Tabs by CoderzHeaven"
  	android:layout_width="fill_parent"
  	android:textStyle="bold"
  	android:textSize="20sp"
  	android:layout_weight="1"
  	android:textColor="@drawable/black"
  	android:padding="5dp"
  	android:gravity="center">
  </Button>

 <LinearLayout
     	android:id="@+id/l1"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:gravity="center_horizontal"
	    android:layout_alignParentBottom="true">

    <include layout="@layout/footer_tabs"/>
 </LinearLayout>
 </RelativeLayout>

Note : Please include the resources as needed.

Custom Tabs in Android

Custom Tabs in Android


Please leave your valuable comments of you found this post useful.

Complete source code can be found here

SlidingDrawer in Android, A simple example.

Sliding-Drawer in a nice and useful widget in android.

Please check one of my previous posts to do this in another way.

How to show a sliding window from below in Android?

Here is a simple example to demonstrate this.

Sliding Drawer in Android

Sliding Drawer in Android

Sliding Drawer in Android

Create a project named SlidingDrawerDemo 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.View.OnClickListener;
import android.widget.Button;
import android.widget.SlidingDrawer;
import android.widget.Toast;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

public class slidingDrawerDemo extends Activity implements OnClickListener {

	Button slideButton,b1, b2,b3,b4;
	SlidingDrawer slidingDrawer;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		slideButton = (Button) findViewById(R.id.slideButton);
		slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer);
		b1 = (Button) findViewById(R.id.Button01);
		b2 = (Button) findViewById(R.id.Button02);
		b3 = (Button) findViewById(R.id.Button03);
		b4 = (Button) findViewById(R.id.Button04);

		b1.setOnClickListener(this);
		b2.setOnClickListener(this);
		b3.setOnClickListener(this);
		b4.setOnClickListener(this);

		slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				slideButton.setBackgroundResource(R.drawable.closearrow);
			}
		});

		slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				slideButton.setBackgroundResource(R.drawable.openarrow);
			}
		});
	}

	@Override
	public void onClick(View v) {
		Button b = (Button)v;
		Toast.makeText(slidingDrawerDemo.this, b.getText() + " Clicked", Toast.LENGTH_SHORT).show();
	}
}

Here is the main.xml code. Make sure to put the resources in the res/drawable folder.

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

	<TextView
		android:text="SlidingViewer Demo from CoderzHeaven"
		android:gravity="center|center_vertical"
		android:textColor="#ff0000"
		android:textSize="25sp"
		android:textStyle="bold|italic"
		android:id="@+id/TextView01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</TextView>

	<SlidingDrawer
		android:layout_width="wrap_content"
		android:id="@+id/SlidingDrawer"
		android:handle="@+id/slideButton"
		android:content="@+id/contentLayout"
		android:padding="10dip"
		android:layout_height="250dip"
		android:orientation="vertical">
			<Button android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:id="@+id/slideButton"
				android:background="@drawable/closearrow">
			</Button>
			<LinearLayout
				android:layout_width="wrap_content"
				android:id="@+id/contentLayout"
				android:orientation="vertical"
				android:gravity="center"
				android:padding="10dip"
				android:background="@drawable/bkg1"
				android:layout_height="wrap_content">
			<Button
				android:id="@+id/Button01"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:background="@drawable/yellow_button"
				android:layout_margin="2dp"
				android:text="Option1">
			</Button>
			<Button
				android:id="@+id/Button02"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:background="@drawable/blue_button"
				android:layout_margin="2dp"
				android:text="Option2"></Button>
			<Button android:id="@+id/Button03"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:layout_margin="2dp"
				android:background="@drawable/yellow_button"
				android:text="Option3">
			</Button>
			<Button android:id="@+id/Button04"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:layout_margin="2dp"
				android:background="@drawable/blue_button"
				android:text="Option4">
			</Button>
		</LinearLayout>
	</SlidingDrawer>
</LinearLayout>

PLease leave your valuable comments on this post.