How to call a function in background in Xcode(iPhone)?

“performSelectorInBackground” will call anyfunction to execute in background and you can also pass string parameters with this method or if you want to pass more params then pass the parameters as an object.

[self performSelectorInBackground:@selector(myBackgroundMethod:) withObject:@"String Params"];

How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

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

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

		ArrayList<String> my_array = new ArrayList<String>();
		my_array = getTableValues();

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

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 read and write files to SDCARD and application SandBox in Android – A complete example?

Here is a complete example of How to read and write files to SDCARD and application SandBox in Android.

First create a new project and inside the mainActivity paste this code.

package com.coderzheaven.filesexample;

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

public class MainActivity extends Activity implements OnClickListener {

	EditText edittext;
	Button b1, b2, b3, b4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        edittext = (EditText)findViewById(R.id.ed);
        edittext.setLines(10);
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
        b4 = (Button)findViewById(R.id.button4);
        
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);        
        
    }
	@Override
	public void onClick(View v) {
		int id = v.getId();
		MyFile file = new MyFile(v.getContext());
		
		switch(id){
			case R.id.button1:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSD(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button2:
				edittext.setText(file.readFromSD());
				break;
			
			case R.id.button3:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSandBox(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button4:
				edittext.setText(file.readFromSandBox());
				break;
		}
		
		
		
	}

}

Now create another class named MyFile.java and copy this code into it.

package com.coderzheaven.filesexample;

import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class MyFile {

	String TAG = "MyFile";
	Context context;
	public MyFile(Context context){
		this.context = context;
	}
	
	public Boolean writeToSD(String text){
		Boolean write_successful = false;
		 File root=null;  
	        try {  
	            // check for SDcard   
	            root = Environment.getExternalStorageDirectory();  
	            Log.i(TAG,"path.." +root.getAbsolutePath());  
	  
	            //check sdcard permission  
	            if (root.canWrite()){  
	                File fileDir = new File(root.getAbsolutePath());  
	                fileDir.mkdirs();  
	  
	                File file= new File(fileDir, "samplefile.txt");  
	                FileWriter filewriter = new FileWriter(file);  
	                BufferedWriter out = new BufferedWriter(filewriter);  
	                out.write(text);  
	                out.close();  
	                write_successful = true;
	            }  
	        } catch (IOException e) {  
	            Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
	            write_successful = false;
	        }  
		return write_successful;
	}
	
	public String readFromSD(){
		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard,"samplefile.txt");
		StringBuilder text = new StringBuilder();
		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;
		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		}
		return text.toString();
	}

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("static-access")
	public Boolean writeToSandBox(String text){
		Boolean write_successful = false;
		try{
			FileOutputStream fOut = context.openFileOutput("samplefile.txt",
					context.MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			osw.write(text);
			osw.flush();
			osw.close();
		}catch(Exception e){
			write_successful = false;
		}
		return write_successful;
	}
	public String readFromSandBox(){
		String str ="";
		String new_str = "";
		try{
			FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);
           
			while((str=br.readLine())!=null)
            {
				new_str +=str;
				System.out.println(new_str);
            }            
		}catch(Exception e)
		{			
		}
		return new_str;
	}
}

Now the layout for the xml file.

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

    <EditText
        android:id="@+id/ed"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
		android:lines="5" android:gravity="top|left" android:inputType="textMultiLine"
		android:scrollHorizontally="false" 
		android:minWidth="10.0dip"
		android:maxWidth="5.0dip"
        android:layout_weight="1"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to SDCARD" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from SDCARD" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to Application SandBox" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from Application SandBox" />

</LinearLayout>

Note you should give this permission in the AndroidManifest file.

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

OK Done. Now run the project.

To view the files

1. To see the SDCARD
Open File explorer -> expand sdcard (or mnt/sdcard).
2. To see the Application SANDBOX
Open File explorer -> expand data/data/your_package_name/files.

Files Example

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post

How to make a Button appear like a TextView in Android?

Hello all…..

This is a simple trick where we can make the Button appear like a TextView in Android.

This is done by setting the background of Button to null like this.

b.setBackgroundDrawable(null);

This is the xml that contains the button.

<?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_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:textColor="#FFF"
    android:id="@+id/but"
    />
</LinearLayout>

How to create a widget in android?

Hello everyone…

Today I will show you how to create a simple widget in android?

First create a new project and name it “Widget1” and name the activity “WidgetDemo1“.
Actually we dont need the activity class here. You can delete it and delete the corresponding entry of it from the AndroidManifest file also.

Now we will make the layout for the widget.

We will make the layout to be the main.xml.
So modify the contents of main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:orientation="vertical"
	android:background="@drawable/yellow_bkg"
	android:layout_gravity="center"
	android:layout_height="wrap_content">
<TextView android:id="@+id/widget_textview"
	android:text="Hello CoderzHeaven"
	android:layout_height="wrap_content"
	android:layout_width="wrap_content"
	android:layout_gravity="center"
	android:layout_margin="5dip"
	android:padding="10dip"
	android:textColor="@android:color/black"/>
</LinearLayout>

Now you may have some errors like resource not found etc.

So now create an xml inside res/drawable folder and name it “yellow_bkg.xml” and copy this code into it.

This will be the background for our widget. However you can have your own background.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f3ae1b" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f3ae1b"
                android:endColor="#bb6008"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Now modify the AndroidManifest.xml.

<?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">
        <!-- This part is for the Widget -->
        <receiver android:name=".MyWidget" android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
			</intent-filter>
			<meta-data android:name="android.appwidget.provider"
			android:resource="@xml/simple_widget" />
		</receiver>
    </application>
</manifest> 

The meta-tag tells android about your widget provider. In this case, the widget provider is located at
res/xml/simple_widget.xml. The provider.xml is pretty much self explaining:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:minWidth="150dip"
	android:minHeight="70dip"
	android:updatePeriodMillis="10000"
	android:initialLayout="@layout/main"
/>

updatePerdiodMillis is the time in milliseconds to update your widget. In our
case, this is unimportant and we don’t need it because we don’t do any update on our widget.

Now create a new class and name it “MyWidget” and set AppWidgetProvider as super class.
Look at the screenshot.

Widget 1

MyWidget.java will look like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetProvider;

public class MyWidget extends AppWidgetProvider {

}

These are the contents of strings.xml

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

Now we have created the widget and you can now run the application.

Widget 1

Widget 1

Widget 1

Please comment if this post was useful.
please share it so that it can be useful to others.

How to override hardware Home button in android? OR How to listen to home button click in android?

Hello everyone…

In this post I will show you how to listen to hardware button in an android smartphone.

This post especially shows how to listen to the home button in android. But my advice is never override the home button in your app.
Home button is to move the currently running process to background. But you can override the Backbutton and other buttons, android allows that on the keyDown Method. But if you try to match the “Home” button in the keyDown method it will not work. For that we have to follow another way which is shown in this post.

This simple java code handles the button pressed.

package test.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;

public class Test2Activity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        	System.out.println("KEYCODE_HOME");
        	showDialog("'HOME'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	System.out.println("KEYCODE_BACK");
        	showDialog("'BACK'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
        	System.out.println("KEYCODE_MENU");
        	showDialog("'MENU'");
            return true;
        }
        return false;
    }
    
    void showDialog(String the_key){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
    		  .setCancelable(true)
    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   dialog.cancel();
    	        	   finish();
    	           }
    	       })
    	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.setTitle("CoderzHeaven.");
    	alert.show();
    }
    
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
    }
    
    public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }
}

When “onUserLeaveHint()” function is defined you can actually listen to the home button press and do some saving of data or something.

 public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }

Home button override

Home button override

Home button override

Please leave your comments on this post and share it on the social Networks.

How to create a Custom Toggle Button in android?

Hello everyone…

In today’s tutorial I will show you how to create a custom toggle button in android. Often in our applications we don’t need a default toggle button, so I will show you how to change that to make a toggle button according to your need.

First I will create a fresh project named “CustomToggleButton” and name the main activity “CustomToggleButtonDemo”.

Now These are the two images that I am using to create the toggle button.

add icon

delete icon

First the layout file main.xml that contains the toggle button.

<?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"
    />
<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	style="@style/OurThemeName" 
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

</LinearLayout>

This will create a toggle button.

Now we will make an xml that contains the resource definition that applies when the button toggles and the background of the button.
We will make the button background transparent and for toggle action we will create another xml that contains the “on” and “off” resource for the button.

Create a new file inside the drawable folder and name it “btn_toggle_bg.xml” and copy this code to it.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background" android:drawable="@android:color/transparent" />
    <item android:id="@+android:id/toggle" android:drawable="@drawable/btn_toggle" />
</layer-list>

Now create another xml inside the drawable folder and name it “btn_toggle.xml” and it contains …

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/add_icon" />
    <item android:state_checked="false" android:drawable="@drawable/delete_icon" />
</selector>

This means that when the button is on(true) the image will be “add_icon.png” and when “off” the image will be “delete_icon.png”.

Now we are going to write a theme that is to be applied to the toggle button that overrides the default android theme.

Create a new file called “themes.xml” inside the strings folder and copy this code to it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Overwrite the ToggleButton style -->
<style name="Widget.Button.Toggle" parent="android:Widget">
    <item name="android:background">@drawable/btn_toggle_bg</item>
    <item name="android:textOn">Add</item>
    <item name="android:textOff">Del</item>
    <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>

<style name="OurThemeName"  parent="@android:Theme.Black">
    <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
      <item name="android:textOn"></item>
    <item name="android:textOff"></item>
</style>
</resources>

Please look at the main.xml file where this theme has been applied.

Here

<ToggleButton 
	android:background="@drawable/btn_toggle_bg"
	<strong>style="@style/OurThemeName" </strong>
	android:checked="true"
	android:id="@+id/ToggleButton01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</ToggleButton>

OK now our custom toggle button is ready. Go on and run it.

Custom toggle button

Custom toggle button

Actually we dont need the activity java file because everything can be done in the xml itself.

Download the complete source code from here.

How to read and write a text file that is stored in your application sandbox in ANDROID?

Hi all…..

In this post I will show you how to read a text file in ANDOID.
Let your file is in the your application sandbox of your ANDOID project, i.e the file’s location is /data/data/your_package_name folder.
To view this folder -> open File Explorer and expand each folder.
For this example to work first push te file into this folder, because I am not creating it now.
The file is named “myfile.txt”

This example reads the file line by line using readLine() function till the end of the file. Here your need two classes named “InputStreamReader” and “BufferedReader”. For writing into the file you need “OutputStreamReader” class. The result is displayed in a Toast. Make sure you notice it.

The following is the code for reading the text file………

String     res  =    null;
try {

	   InputStream       in = openFileInput("myfile.txt");

	   if (in != null) {
	    // prepare the file for reading
	     InputStreamReader input = new InputStreamReader(in);
	     BufferedReader buffreader = new BufferedReader(input);

	      res = "";
	      while (( line = buffreader.readLine()) != null) {
	      	res += line;
	      }
	      in.close();
	      Toast.makeText(getApplicationContext(),"File Contents ==> " + res,Toast.LENGTH_SHORT).show();
          }else{
	    }

} catch(Exception e){
       Toast.makeText(getApplicationContext(),     e.toString() +   e.getMessage(),Toast.LENGTH_SHORT).show();
}

Want More then

Follow this link

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Please leave your comments on this post.

How to change the background color of a Layer in Cocos2D using CCColorLayer?

Set background color to magenta.

CCColorLayer* colorLayer = [CCColorLayer layerWithColor:ccc4(255, 0, 255, 255)];
[self addChild:colorLayer z:0];

//Changing the color of a sprite....

((CCSprite*)node).color = ccRED; // This will change the sprite color to RED.

How to inherit from other styles or how to extend your own styles in android?

Hello all….
I have covered many tutorials on styles on how to implement and use them.
Today I will show you how to inherit from other styles or how to extend a style already created by you and use it for applying to other views.

Here is one of my previous posts.
http://www.coderzheaven.com/2012/02/03/changing-the-style-or-theme-of-default-alertdialog-in-android/
Another one is here..
http://www.coderzheaven.com/2011/06/19/styling-text-in-android-through-xml/

OK We will start now.

First I will show you my main.xml
It contains only one simple 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="Hello World, Coderzheaven"
 />
   
</LinearLayout>

OK now we are going to apply a style to the textview, for that I am creating a file named “styles.xml” inside the values folder.
And inside the styles.xml copy this code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="RedLabel">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:typeface">monospace</item>
		<item name="android:background">#F00</item>
		<item name="android:textColor">#FFF</item>
	</style>
</resources>
1


Now we will apply this style to the textview like this -> by providing it as style to the textview in the xml.
1
<TextView    
	 android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Hello World, Coderzheaven"
     style="@style/RedLabel"
     />

Now we will create another style and name it ButtonStyle aand apply it to a button. But the main thing is that this new style is inherited from the style we previously created. i.e the first style will be the parent of the second thus extending the first one. Our styles.xml will look like this now.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="RedLabel">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:typeface">monospace</item>
		<item name="android:background">#F00</item>
		<item name="android:textColor">#FFF</item>
	</style>
	
 	<style name="ButtonStyle" parent="RedLabel">
		<item name="android:layout_width">wrap_content</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:textSize">15px</item>
		<item name="android:typeface">serif</item>
	</style>

</resources>

Now we will apply this style to a button inside the main.xml(Do this after placing a button control inside main.xml)

Our new main.xml will now 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:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Hello World, Coderzheaven"
     style="@style/RedLabel"
     />
 
 <Button    
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="This is a button"
     style="@style/ButtonStyle"
 />   
</LinearLayout>

i.e. We can extend this second style and soon. That’s the power of styles in xml.

This the main java file. Actually we don’t need this .

package com.coderzheaven.pack;

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

public class StyleDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Please leave your valuable comments on this post so that I can improve it.

How to set a Bitmap Image as Source of an image in Windows Phone 7?

This is a sample code snippet that adds a Bitmap as Source of an image in windows phone 7.

            Uri uri = new Uri("Background.png", UriKind.Relative);
            StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(resourceInfo.Stream);
            image1.Source = bmp;

Assuming you have placed an image in the UI and named it image1.

Custom GridView in android. A simple example.

Hello all………..

Android has been absoultely wonderful for customizing widgets. I have shown a lot of example to customize ListViews, spinners etc.
Today I will show you how to customize gridviews.
Using this method you can actually place anything inside a gridview even a webview also.

So here we start.
We customize a gridview by creating an adapter that extends “BaseAdapter”.
This is the class that extends “BaseAdapter” and create a customAdapter.

 public class MyAdapter extends BaseAdapter {

    	private Context mContext;

		public MyAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {
			return mThumbIds.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mThumbIds[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View grid;

			if(convertView==null){
				grid = new View(mContext);
				LayoutInflater inflater=getLayoutInflater();
				grid=inflater.inflate(R.layout.mygrid_layout, parent, false);
			}else{
				grid = (View)convertView;
			}

			ImageView imageView = (ImageView)grid.findViewById(R.id.image);
			imageView.setImageResource(mThumbIds[position]);

			return grid;
		}

	}

Acually we can provide any custom layout for the view inside the gridview that is for each cell.

The xml I am using here is “mygrid_layout.xml” which looks like this.

<?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="wrap_content"
	android:background="@drawable/customshape_header"
	android:orientation="vertical">
	<ImageView
		android:id="@+id/image"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"/>
</LinearLayout>

This is the custom shape header class which is used for styling which is saved in res/drawable folder.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp" />
    <solid android:color="#660033"/>
    <stroke
        android:width="1dip"
        android:color="#C0C0C0" />
</shape>

Now the full source code for implementing this class.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class CustomGridViewExample extends Activity {

	private Integer[] mThumbIds = {
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			};


	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new MyAdapter(this));
        gridview.setNumColumns(4);
    }

  public class MyAdapter extends BaseAdapter {

    	private Context mContext;

		public MyAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {
			return mThumbIds.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mThumbIds[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View grid;

			if(convertView==null){
				grid = new View(mContext);
				LayoutInflater inflater=getLayoutInflater();
				grid=inflater.inflate(R.layout.mygrid_layout, parent, false);
			}else{
				grid = (View)convertView;
			}

			ImageView imageView = (ImageView)grid.findViewById(R.id.image);
			imageView.setImageResource(mThumbIds[position]);

			return grid;
		}
	}
}

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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:padding="10dp"
    android:gravity="center"
    android:textStyle="bold"
    />

<GridView
	android:id="@+id/gridview"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:numColumns="auto_fit"
	android:verticalSpacing="10dp"
	android:horizontalSpacing="10dp"
	android:stretchMode="columnWidth"
	android:gravity="center"
	android:scrollbars="none" />
</LinearLayout>
Custom GridView in Android

Custom GridView in Android

You can download the complete source code from here.

ListView with Sections in android.

Hello all……….

We have seen many posts about ListViews like creating a listview, adding data to it, customizing a listview etc.

Take a look at some of these examples

1. Single Selection ListView in android
2. Flitering a ListView using an input from an EditText in Android.
3. How to create a custom ListView in android?
4. Android dialog with ListView.
5. Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.
6. Android listView with icons.
7. Creating scrolling ListView in android.

ListView with sections in android

ListView with sections in android

Today also we will see another customization of listviews.
Today I will show you how to create listviews with sections.

This is the main.xml layout file which contains 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"
    android:background="@drawable/orange"
    >
    <ListView
		 	android:id="@+id/list1"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:background="@drawable/bg_transparent"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:divider="@drawable/green"
			android:dividerHeight="1px"
			android:padding="0dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginTop="5dip"
		    android:layout_marginLeft="5dip"
		    android:layout_marginRight="5dip"
		    android:layout_marginBottom="5dip"
		    android:layout_weight="1"/>

</LinearLayout>

I am using some resources in this, one of which is the “customshape_header.xml” file which is saved in res/drawable directory.
This will ptovide the background for the section header.
customshape_header.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="3dp" />
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="1dip"
        android:color="#C0C0FF" />
</shape>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ListView with Sections</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="orange">#FFA500</drawable>
	<drawable name="darkgrey">#606060</drawable>
</resources>

This is the “lv_layout.xml” file which I am using for each row in 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"
    android:id="@+id/l1"
    >
</LinearLayout>

Now the main java file which implements the logic for creating the listview with sections.

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SectionListViewDemo extends Activity {

	ListView L1;
	myAdapter myadp;
	String last_item = "B";
	static final String[] labels_array = new String[] {
		  "Afghanistan", "Albania",
		  "Bahrain", "Bangladesh",
		  "Cote d'Ivoire", "Cambodia",
		  "Estonia", "Ethiopia", "Faeroe Islands",
		  "Former Yugoslav Republic of Macedonia"
		};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        L1 = (ListView)findViewById(R.id.list1);
        myadp = new myAdapter(this,labels_array);
        L1.setAdapter(myadp);

        L1.setOnItemClickListener(new OnItemClickListener(){
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    				long arg3) {
    		}
    	});
    }

    /* The adapter class.... */
    class myAdapter extends ArrayAdapter<String>
    {
  	   TextView label;
  	   View row;
  	   public myAdapter(Context context,String[] arr)
  	   {
  		    super(context, android.R.layout.simple_list_item_1, arr);
  	   }

  	   public View getView(int position, View convertView, ViewGroup parent)
  		{
  	 		   try{
  	 				LayoutInflater inflater=getLayoutInflater();
  	 				row = inflater.inflate(R.layout.lv_layout, parent, false);

  	 				LinearLayout L1 = (LinearLayout)row.findViewById(R.id.l1);
  	 				TextView header = new TextView(getApplicationContext());
  	 				L1.addView(header);
  	 				TextView label = new TextView(getApplicationContext());
  	 				L1.addView(label);
  					System.out.println("LAST : " + last_item);
  					header.setText(last_item);
  					label.setText(labels_array[position]);
  					label.setPadding(4, 1, 1, 1);
  					L1.setPadding(4, 4, 4, 4);

  					label.setTextColor(Color.BLACK);

  					if(!labels_array[position].substring(0,1).equalsIgnoreCase(last_item)){
  						System.out.println("ADD :  " + last_item);
  						header.setBackgroundResource(R.drawable.customshape_header);
  						header.setPadding(4, 1, 1, 1);
  						row.setEnabled(false);
  						header.setTextColor(Color.BLACK);
  						header.setText(labels_array[position].substring(0,1));
  						//label.setVisibility(View.GONE);
  						//position-=2;
  					}else{
  						System.out.println("REM :  " + last_item);
  						header.setVisibility(View.GONE);
  					}
  					last_item = labels_array[position].substring(0,1);

  	 		   }catch(Exception e){

  			   }
  		    return row;
  		}
    }
}

Now its ready to run the application.

Please leave your valuable comments 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.

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.

How to use shapes in android? A simple example.

In android with shapes we can create beautiful layouts.
Lets look at an example.

Create an xml named “gradient.xml” in your drawable folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="0"
        android:startColor="#000000"
        android:endColor="#000000"
        android:centerColor="#97CF4D" />
</shape>

Now the main layout file main.xml

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

    <TextView
        android:text="Sample Text"
        android:id="@+id/text01"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
   <TextView
        android:text="Sample text"
        android:id="@+id/text02"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>

    <EditText
        android:text=" "
        android:id="@+id/text03"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </EditText>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
</LinearLayout>

The main java file.

package pack.coderzheaven;

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

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

Done. You can now run the application.

Using Shapes

Using Shapes

How to send email from and ANDROID Application programatically?

Hello all……..
In today’s post I will show you send mail from an android application progrmatically..
Let’s go to the code fast……
This is the code in the mail java file….

package com.coderzheaven;

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;
import android.widget.Toast;

public class sendMailDemo extends Activity {
    Button send;
    EditText address, subject, emailbody;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        address = (EditText) findViewById(R.id.address);
        subject = (EditText) findViewById(R.id.subject);
        emailbody = (EditText) findViewById(R.id.body);
        send = (Button) findViewById(R.id.send);

        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	sendEmail();
            }
        });
    }

    public void sendEmail(){

    	if(!address.getText().toString().trim().equalsIgnoreCase("")){
    	  final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
	      emailIntent.setType("plain/text");
	      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ address.getText().toString()});
	      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
	      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailbody.getText());
	      sendMailDemo.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	    }
    	else{
    		Toast.makeText(getApplicationContext(), "Please enter an email address..", Toast.LENGTH_LONG).show();
    	}
      }
	}

Now the layout file (main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:background="@drawable/android"
	>
	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:id="@+id/emailaddress"
		android:text="Email Address"
		android:textStyle="bold">
	</TextView>

	<EditText
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:width="250dip"
		android:hint="email address"
		android:id="@+id/address">
	</EditText>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Subject"
		android:textStyle="bold">
	</TextView>

	<EditText
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:width="250dip"
		android:hint="Subject"
		android:id="@+id/subject">
	</EditText>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Your Message"
		android:textStyle="bold">
	</TextView>
	<EditText
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:lines="5"
		android:hint="Your message here!!"
		android:id="@+id/body">
	</EditText>
	<Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:id="@+id/send"
		android:text="Send Email"
		android:width="150dip">
	</Button>
</LinearLayout>

The AndroidManifest.xml

<?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">
    <application android:icon="@drawable/icon" android:label="Send Mail Demo">
        <activity android:name=".sendMailDemo"
                  android:label="Send Mail Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Note: However if you test this in your emulator, it will not work. Install it in your device to test it.

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!

Android frame Animation

A series of frames is drawn one after the other at regular intervals.
For this create a xml which contains ImageView for showing the animation

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


   <ImageView
      android:id="@+id/Image"
       android:layout_gravity="center_horizontal"
      android:layout_width="wrap_content"
      android:background="@drawable/d1"
      android:layout_height="wrap_content"/>

      <Button
      android:id="@+id/startFAButtonId"
      android:layout_width="wrap_content"
      android:layout_gravity="center_horizontal"
      android:layout_height="wrap_content"
      android:text="Start Animation"
      />
</LinearLayout>

The main java file is

package com.coderzheaven.animation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class Frame extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button b = (Button)this.findViewById(R.id.startFAButtonId);
        b.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v)
			{
				animate();
			}
		});

    }
 	   private void animate() {
 	      ImageView imgView = (ImageView)findViewById(R.id.Image);
 	      imgView.setVisibility(ImageView.VISIBLE);
 	      imgView.setBackgroundResource(R.drawable.animation_frame);

 	      AnimationDrawable frameAnimation =  (AnimationDrawable) imgView.getBackground();

 	      if (frameAnimation.isRunning()) {
 	         frameAnimation.stop();
 	      }
 	      else {
 	         frameAnimation.stop();
 	         frameAnimation.start();
 	      }
 	   }
 }

Next the main part, an xml which holds each image and duration in which each image shows.
The xml should be placed inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<animation-list
	 xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
   <item android:drawable="@drawable/d1" android:duration="50" />
   <item android:drawable="@drawable/d2" android:duration="50" />
   <item android:drawable="@drawable/d3" android:duration="50" />
   <item android:drawable="@drawable/d4" android:duration="50" />
   <item android:drawable="@drawable/d5" android:duration="50" />
</animation-list>

When i click the button the animation will start

SQLiteManager plugin for eclipse

When you are working on an Android application that stores data in a SQLite database.There arise many questions like
where does this database file get stored on the filesystem ?
How can we access the database?

I will give solution to all these problems. I created the database from my previous post
about Using SQLite in ANDROID

You can see the sqlite database in eclipse by opening File Explorer .Then

/data/data/package_name/databases

But here we cannot see the tables and table data.
For viewing the table details Eclipse has a plugin. You can download the jar from below.

Download the jar from the sqlite manager from here.

Now put the jar in the folder


eclipse/dropins/


and restart the eclipse and now you can see the sqlitemanager plugin on the top right of the File Explorer window

SQLite

By clicking the icon, sqliteManager Window comes and here we can see the table structure.

SQLite

and then the Browse Data tab shows the whole data
SQLite

Hopefully i think you cleared all doubts about SqliteManager Plugin

Note : If you’re using a plug-in for which no Update Site is available, you can use the “dropins” folder in your Eclipse installation directory.

Plug-ins are typically distributed as .jar files. To add a plug-in to your Eclipse installation, put the plug-in .jar file into the Eclipse “dropins” folder and restart Eclipse. Eclipse should detect the new plug-in and install it for you.

Note : if your SQLiteManager Plugin is not enabled, then check your sqlite db file extension. It should be a “.db” extension.

Please check my another ANDROID BLOG FOR MORE ANDROID CODES AND SAMPLES.

How to use SQLite in ANDROID, A really simple example.

Hello ANDROID Lovers……..

In today’s tutorial I will show you how to deal with SQLite Databases in ANDROID. You know that SQLite are Lightweight databases which is maintained only on the client side. They don’t need a server. The SQLite databases are simply a file wrapped around with some stuff which helps us deal with them like a normal database. And also don’t think they are like other databases like MySQL, Oracle etc, SQLite databases provide basic funtionalities to deal with a database.

Here I will show you how to use simple queries to deal with the SQLite database.
You may have found on the net numerous examples for SQLite in ANDROID using some extra classes which extend SQLiteOpenHelper classes which is pretty difficult to understand
But Don’t worry here I will show you how to deal with these databases like you normally do with your MYSQL Database or Oracle.

Before you need some resources.
1. An image “android.png” or “android.jpg” (which I am using as background for the layout).
OK that’s enough

=====================================================================================================================
Now go on and create a new project and name it “SQLiteExample.java” and drag and copy the following code to it.

SQLiteExample.java

package pac.SQLite;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SQLiteExample extends Activity {

	LinearLayout Linear;
	SQLiteDatabase mydb;
	private static String DBNAME = "PERSONS.db";	// THIS IS THE SQLITE DATABASE FILE NAME.
	private static String TABLE = "MY_TABLE";		// THIS IS THE TABLE NAME

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

        Linear  = (LinearLayout)findViewById(R.id.linear);
        Toast.makeText(getApplicationContext(), "Creating table.", Toast.LENGTH_SHORT).show();

        dropTable();		// DROPPING THE TABLE.
        createTable();
        TextView t0 = new TextView(this);
    	t0.setText("This tutorial covers CREATION, INSERTION, UPDATION AND DELETION USING SQLITE DATABASES.                                                Creating table complete........");
    	Linear.addView(t0);
        Toast.makeText(getApplicationContext(), "Creating table complete.", Toast.LENGTH_SHORT).show();
        insertIntoTable();
        TextView t1 = new TextView(this);
    	t1.setText("Insert into table complete........");
    	Linear.addView(t1);
        Toast.makeText(getApplicationContext(), "Insert into table complete", Toast.LENGTH_SHORT).show();
        TextView t2 = new TextView(this);
    	t2.setText("Showing table values............");
    	Linear.addView(t2);
    	showTableValues();
        Toast.makeText(getApplicationContext(), "Showing table values", Toast.LENGTH_SHORT).show();
        updateTable();
        TextView t3 = new TextView(this);
    	t3.setText("Updating table values............");
    	Linear.addView(t3);
        Toast.makeText(getApplicationContext(), "Updating table values", Toast.LENGTH_SHORT).show();
        TextView t4 = new TextView(this);
    	t4.setText("Showing table values after updation..........");
    	Linear.addView(t4);
        Toast.makeText(getApplicationContext(), "Showing table values after updation.", Toast.LENGTH_SHORT).show();
        showTableValues();
        deleteValues();
        TextView t5 = new TextView(this);
    	t5.setText("Deleting table values..........");
    	Linear.addView(t5);
        Toast.makeText(getApplicationContext(), "Deleting table values", Toast.LENGTH_SHORT).show();
        TextView t6 = new TextView(this);
    	t6.setText("Showing table values after deletion.........");
    	Linear.addView(t6);
        Toast.makeText(getApplicationContext(), "Showing table values after deletion.", Toast.LENGTH_SHORT).show();
        showTableValues();
        setColor(t0);
        setColor(t1);
        setColor(t2);
        setColor(t3);
        setColor(t4);
        setColor(t5);
        setColor(t6);
    }
    // THIS FUNCTION SETS COLOR AND PADDING FOR THE TEXTVIEWS 
    public void setColor(TextView t){
    	t.setTextColor(Color.BLACK);
    	t.setPadding(20, 5, 0, 5);
    	t.setTextSize(1, 15);
    }

    // CREATE TABLE IF NOT EXISTS 
    public void createTable(){
    	try{
    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
    	mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
    	mydb.close();
    	}catch(Exception e){
    		Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG);
    	}
    }
    // THIS FUNCTION INSERTS DATA TO THE DATABASE
    public void insertIntoTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('ANTHONY','USA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SHUING','JAPAN')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('JAMES','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('SOORYA','INDIA')");
	    	mydb.execSQL("INSERT INTO " + TABLE + "(NAME, PLACE) VALUES('MALIK','INDIA')");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION SHOWS DATA FROM THE DATABASE 
    public void showTableValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	Cursor allrows  = mydb.rawQuery("SELECT * FROM "+  TABLE, null);
	    	System.out.println("COUNT : " + allrows.getCount());
	    	Integer cindex = allrows.getColumnIndex("NAME");
	    	Integer cindex1 = allrows.getColumnIndex("PLACE");

	    	TextView t = new TextView(this);
	    	t.setText("========================================");
			//Linear.removeAllViews();
			Linear.addView(t);

			if(allrows.moveToFirst()){
				do{
					LinearLayout id_row   = new LinearLayout(this);
					LinearLayout name_row = new LinearLayout(this);
					LinearLayout place_row= new LinearLayout(this);

					final TextView id_  = new TextView(this);
					final TextView name_ = new TextView(this);
					final TextView place_ = new TextView(this);
					final TextView   sep  = new TextView(this);

					String ID = allrows.getString(0);
			    	String NAME= allrows.getString(1);
			    	String PLACE= allrows.getString(2);

			    	id_.setTextColor(Color.RED);
			    	id_.setPadding(20, 5, 0, 5);
			    	name_.setTextColor(Color.RED);
			    	name_.setPadding(20, 5, 0, 5);
			    	place_.setTextColor(Color.RED);
			    	place_.setPadding(20, 5, 0, 5);

					System.out.println("NAME " + allrows.getString(cindex) + " PLACE : "+ allrows.getString(cindex1));
					System.out.println("ID : "+ ID  + " || NAME " + NAME + "|| PLACE : "+ PLACE);

					id_.setText("ID : " + ID);
					id_row.addView(id_);
					Linear.addView(id_row);
					name_.setText("NAME : "+NAME);
					name_row.addView(name_);
					Linear.addView(name_row);
					place_.setText("PLACE : " + PLACE);
					place_row.addView(place_);
					Linear.addView(place_row);
					sep.setText("---------------------------------------------------------------");
					Linear.addView(sep);
				}
				while(allrows.moveToNext());
			}
			mydb.close();
    	 }catch(Exception e){
 			Toast.makeText(getApplicationContext(), "Error encountered.", Toast.LENGTH_LONG);
 		}
	}
    // THIS FUNCTION UPDATES THE DATABASE ACCORDING TO THE CONDITION 
    public void updateTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("UPDATE " + TABLE + " SET NAME = 'MAX' WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNCTION DELETES VALUES FROM THE DATABASE ACCORDING TO THE CONDITION
    public void deleteValues(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DELETE FROM " + TABLE + " WHERE PLACE = 'USA'");
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while deleting.", Toast.LENGTH_LONG);
		}
    }
    // THIS FUNTION DROPS A TABLE 
    public void dropTable(){
    	try{
	    	mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
	    	mydb.execSQL("DROP TABLE " + TABLE);
	    	mydb.close();
	    }catch(Exception e){
			Toast.makeText(getApplicationContext(), "Error encountered while dropping.", Toast.LENGTH_LONG);
		}
    }
}

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">
	<ScrollView
		android:id="@+id/ScrollView01"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="@drawable/android">
			<LinearLayout
				android:id="@+id/linear"
				android:orientation="vertical"
				android:layout_below="@+id/add_record"
				android:layout_width="wrap_content"
				android:layout_height="fill_parent">
			</LinearLayout>
	</ScrollView>
</LinearLayout>

The mainfest.xml file.

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

=====================================================================================================================

That’s all you are done go on and run the application.
Scroll Down to see different oprations done on the database.
Well if you want to see the database you can go to the DDMS Perspective and open File-Explorer and under folder “data/data/your-application-package/databases/”, there you will see the database.

However there is a way to see the actual database values like your MYSQL Database.
Check this post to see how its done.
SQLiteManager plugin for eclipse
Happy coding…

Fell free to leave your comments if you have any doubt on this.

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Check some other most popular and useful posts.

http://www.coderzheaven.com/2012/08/21/uploading-downloading-files-popular-posts/

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.

Sending your application to background when backbutton is pressed in ANDROID…… OR Detecting whether back Button has been pressed in your ANDROID phone or not.

This code works for all API Levels.

public class MyActivity extends Activity {
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      moveTaskToBack(true);
    }
    return super.onKeyDown(keyCode, event);
  }
}

The below code works for API level 5 or Higher…..

public class MyActivity extends Activity {
   @Override
  public void onBackPressed() {
    moveTaskToBack(true);
  }
}