Tag Archives: Exception

exception

Multiple Selection GridView in Android

This is a simple post that helps you to do multiple selection in a ListView.

Check out previous posts for 3D animation in a Listview.

At first we will see the XML layout file.
This layout contains a gridview since we are dealing with it only.

Multiple Selection GridView

Multiple Selection GridView

grid_1.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myGrid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="60dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:padding="10dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" />

Now the MainActivity that does all the work for the multiple selection in a ListView.

package com.coderzheaven.multipleselectiongrid;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {

	GridView mGrid;

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

		loadApps();

		setContentView(R.layout.grid_1);
		mGrid = (GridView) findViewById(R.id.myGrid);
		mGrid.setAdapter(new AppsAdapter());
		mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
		mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());
	}

	private List<ResolveInfo> mApps;

	private void loadApps() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
	}

	public class AppsAdapter extends BaseAdapter {
		public AppsAdapter() {
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			CheckableLayout l;
			ImageView i;

			if (convertView == null) {
				i = new ImageView(MainActivity.this);
				i.setScaleType(ImageView.ScaleType.FIT_CENTER);
				i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
				l = new CheckableLayout(MainActivity.this);
				l.setLayoutParams(new GridView.LayoutParams(
						GridView.LayoutParams.WRAP_CONTENT,
						GridView.LayoutParams.WRAP_CONTENT));
				l.addView(i);
			} else {
				l = (CheckableLayout) convertView;
				i = (ImageView) l.getChildAt(0);
			}

			ResolveInfo info = mApps.get(position);
			i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));

			return l;
		}

		public final int getCount() {
			return mApps.size();
		}

		public final Object getItem(int position) {
			return mApps.get(position);
		}

		public final long getItemId(int position) {
			return position;
		}
	}

	public class CheckableLayout extends FrameLayout implements Checkable {
		private boolean mChecked;

		public CheckableLayout(Context context) {
			super(context);
		}

		@SuppressWarnings("deprecation")
		public void setChecked(boolean checked) {
			mChecked = checked;
			setBackgroundDrawable(checked ? getResources().getDrawable(
					R.drawable.blue) : null);
		}

		public boolean isChecked() {
			return mChecked;
		}

		public void toggle() {
			setChecked(!mChecked);
		}

	}

	public class MultiChoiceModeListener implements
			GridView.MultiChoiceModeListener {
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			mode.setTitle("Select Items");
			mode.setSubtitle("One item selected");
			return true;
		}

		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return true;
		}

		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			return true;
		}

		public void onDestroyActionMode(ActionMode mode) {
		}

		public void onItemCheckedStateChanged(ActionMode mode, int position,
				long id, boolean checked) {
			int selectCount = mGrid.getCheckedItemCount();
			switch (selectCount) {
			case 1:
				mode.setSubtitle("One item selected");
				break;
			default:
				mode.setSubtitle("" + selectCount + " items selected");
				break;
			}
		}

	}
}

You don’t have have to change anything in the manifest for this to work.
Now go on and run it.

You can download the complete sample code for the above post from here.

Join the Forum discussion on this post

Join the Forum discussion on this post

How to Download a PDF File and open it in Android using an installed PDF Reader?

Actually this is fairly simple.

Open PDF

Open PDF

Open PDF

This simple code does this.

Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					setError("PDF Reader application is not installed in your device");
				}

Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.

package com.example.openpdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tv_loading;
	String dest_file_path = "test.pdf";
	int downloadedSize = 0, totalsize;
	String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
	float per = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tv_loading = new TextView(this);
		setContentView(tv_loading);
		tv_loading.setGravity(Gravity.CENTER);
		tv_loading.setTypeface(null, Typeface.BOLD);
		downloadAndOpenPDF();
	}

	void downloadAndOpenPDF() {
		new Thread(new Runnable() {
			public void run() {
				Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					tv_loading
							.setError("PDF Reader application is not installed in your device");
				}
			}
		}).start();
  
	}

	File downloadFile(String dwnload_file_path) {
		File file = null;
		try {

			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			file = new File(SDCardRoot, dest_file_path);

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are
			// downloading
			totalsize = urlConnection.getContentLength();
			setText("Starting PDF download...");

			// create a buffer...
			byte[] buffer = new byte[1024 * 1024];  
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				per = ((float) downloadedSize / totalsize) * 100;
				setText("Total PDF File size  : "
						+ (totalsize / 1024)
						+ " KB\n\nDownloading PDF " + (int) per
						+ "% complete");
			}
			// close the output stream when complete //
			fileOutput.close();
			setText("Download Complete. Open PDF Application installed in the device.");

		} catch (final MalformedURLException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final IOException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final Exception e) {
			setTextError(
					"Failed to download image. Please check your internet connection.",
					Color.RED);
		}
		return file;
	}

	void setTextError(final String message, final int color) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setTextColor(color);
				tv_loading.setText(message);
			}
		});

	}

	void setText(final String txt) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setText(txt);
			}
		});

	}

}

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

JSON IN ANDROID.

Complex JSON String parsing in ANDROID

http://www.coderzheaven.com/2011/06/10/complex-json-string-parsing-in-android/

Parsing JSON Object in ANDROID.

http://www.coderzheaven.com/2011/06/09/parsing-json-objects-in-android/

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.

Saving Key-Value pair in Windows Phone using IsolatedStorageSettings

This sample code helps you to save a key and a corresponding value in windows Phone inside your application sandbox with the help of isolatedStorageSettings.

PLease check this post before working around this post.

How to save a text file in Windows Phone 7 or How to use isolated storage settings in Windows Phone 7?

Here is the C# code for this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;

namespace IsolatedStorageSettingsDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            iss.Add("site", "coderzheaven.com");
            iss.Save();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            string data = "";

            try
            {
                iss.TryGetValue("site", out data);
                MessageBox.Show(data);
            }
            catch (Exception e1)
            {

            }
        }


    }
}

The stored value will be stored in a MessageBox.
Please leave your valuable comments on this post.

Switch Images in ANDROID.

Hi all ……..

Ofter we have trouble with loading continous images in ANDROID from our application directory.
The reason is that all resources have a unique resource ID which we need to get to load these resources.
The following example shows how to get these unique identifier from the “path” of the resource.
For example Here I have seven images with names sample_0.png, sample_1.png to sample_7.png.
By using
imgID = getResources().getIdentifier(“sample_”+num, “drawable”, “com.switchImages”);
I convert the path to it’s identifier.
Note that all these images need to be in “drawable” folder.
Even if your folder name is “drawable-hdpi” also then give only “drawable” and third parameter the package name.Just copy and paste the following code to your java file.
Make sure that you have all the images in the resource.

package com.switchImages;

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

public class Switch extends Activity {
    ImageView img;
    Button preview;
    int num = 0;
    public int imgID = 0;

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

        img = (ImageView)findViewById(R.id.imageView);
        preview = (Button)findViewById(R.id.Prev);

        try
             {
                 imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                         img.setImageResource(imgID);
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
             }

             preview.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                 imgID = getID();
                                                switchImage(imgID);
                                    }
                        });
    }

    public void switchImage(int ID){
             try
                         {
                                     ID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                                     img.setImageResource(ID);
                         }catch(Exception e){
                                    Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
                         }
    }

    public int getID(){
             int imgID = 0;
             num++;
             if(num > 7) num = 0;
             try
             {
                        imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage(), Toast.LENGTH_SHORT).show();
             }
             return imgID;
    }
}

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

Saving TextFile to SDCARD in android?

Hello android lovers,

In today’s tutorial I will show you how to

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

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

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

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

package com.coderzheaven.pack;

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

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

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

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

This is the main.xml file contents.

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

Here is the Strings.xml file contents

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

Now the AndroidManifest.xml file contents.

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


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

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

Please leave your valuable comments on this post.

How to avoid OutOfMemory Exception in android?

Hello all..

The OutofMemory exception is a common exception in android when you select an image from a gallery or load Big Images in android.
There are different methods to solve this problem.
Today I will show you one of the method to solve this problem.

The method I am going to explain here is to create a virtual device with more

1. RAM
2. Heap Size
3. SDCard support.

The main reason for this problem is that if the virtual device you created has less configuration, then it will not allocate more heap size for bigger images.
In this tutorial I will show you how to create a Virtual device with higher configuration.

Follow these steps

1. Open Eclipse -> Window -> Android SDK and AVD Manager.
2. Click new -> Give a Virtual device name and other details like Target and SDCARD size.
3. In the Hardware tab below click on new
4. See the options in the combobox.
5. Give appropriate values after selecting values from the Box after clicking ok. Try to give bigger values than default


See the figure below.




In the coming posts I will explain another two methods to avoid this exception. Keep in touch.

Click the +1 button on the top to share it with your friends and please leave your valuable comments also.

How to find the device ID or Serial Number of an android device?

Here is a simple API to find the device ID of an android device.
There are many ways to get the device ID in android

    String serial_no = null;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial_no = (String) get.invoke(c, "ro.serialno");
       System.out.println("Device serial ID : " + serial_no);
    } catch (Exception e) {
        System.out.println("Some error occured : " + e.getMessage());
    }

Note : Try this in a real device, then only you will get the device ID.
Also put this permission in the AndroidManifest file

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

Complex JSON String parsing in ANDROID

Hello all…..

In the previous post I have shown you how to parse a Simple JSON String in ANDROID.
In today’s tutorial I will show you how to parse a complex JSON String.
Take a look at the example

Here the JSON String used is

"{"menu": "
    "{"id": "
	 ""file", "value": "File", "popup": "
		 "{ "menuitem": [ {"value": "New",   "onclick": "CreateNewDoc()"}, "
			 "{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}";

Now let’s dothe operation………..

package pack.coderzheaven;

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JSON_Demo extends Activity {
	private JSONObject jObject;
	private String jString = "{"menu": " +
							 "{"id": " +
							 ""file", "value": "File", "popup": " +
							 "{ "menuitem": [ {"value": "New",   "onclick": "CreateNewDoc()"}, " +
							 "{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {

		jObject = new JSONObject(jString);

		JSONObject menuObject = jObject.getJSONObject("menu");
		String attributeId = menuObject.getString("id");
		System.out.println(attributeId);

		String attributeValue = menuObject.getString("value");
		System.out.println(attributeValue);

		JSONObject popupObject = menuObject.getJSONObject("popup");
		JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

		for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}
	}
}

Please check the Logcat for the output.

Please leave your valuable comments on this post.

Parsing JSON Object in ANDROID.

JSON are alternative to XML and easy to understand than XML.
As other languages Java also supports JSON parsing.
Here is a simple example of JSON parsing in ANDROID.

This is the JSON String that I am going to parse.

{"A":
           { "A1":"A1_value" ,"A2":"A2_value","sub":
              { "sub1":[ {"sub1_attr":"sub1_attr_value" }]}
           }
}";

And this JSON is same as this xml.

	  <A A1="A1_value" A2="A2_value">
	 	<sub>
	 		<sub1 sub1_attr="sub1_attr_value" />
	 	</sub>
	   <A>

Here is the code for this parsing.

package pack.coderzheaven;

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JSON_Demo extends Activity {
	private JSONObject jObject;
	private String test = "{"A":  {  "A1":"A1_value" ,"A2":"A2_value", "sub": { "sub1":[ {"sub1_attr":"sub1_attr_value" }] } }    }";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {

		jObject = new JSONObject(test);
		JSONObject menuObject = jObject.getJSONObject("A");
		String attributeId1 = menuObject.getString("A1");
		System.out.println("A1 value == " +attributeId1);
		String attributeId2 = menuObject.getString("A2");
		System.out.println("A2 value == " +attributeId2);

		JSONObject popupObject = menuObject.getJSONObject("sub");
		JSONArray menuitemArray = popupObject.getJSONArray("sub1");

		System.out.println("sub1_attr = " + menuitemArray.getJSONObject(0).getString("sub1_attr").toString());
	}
}

Please check the Logcat for the output.

Posts to come.

More complex JSON String parsing in ANDROID.

Please leave your valuable comments.

How to create and delete a directory in SdCard in ANDROID?

Hi all……

This is a simple example to create and delete a directory in ANDROID.
Here the directly is created in the SDCARD. So first create an SDCARD and start the emulator with the SDCARD.

Let’s look at the program.
Use can use this program to create or delete a file in ANDROID also.

package pack.coderzheaven;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreateDeleteDIR_Example extends Activity {

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

        t = (TextView)findViewById(R.id.tv);
        b= (Button) findViewById(R.id.Button01);
        File dir = new File("/sdcard/new_dir");
        try{
          if(dir.mkdir()) {
             System.out.println("Directory created");
             t.setText("Directory created");
          } else {
             System.out.println("Directory is not created");
             t.setText("Directory is not created");
          }
        }catch(Exception e){
          e.printStackTrace();
        }

        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File del = new File("/sdcard/new_dir");
				 boolean success = del.delete();
			        if (!success) {
			           System.out.println("Deletion of directory failed!");
			        }
			}
        });

    	/* IF THE DIRECTORY IS NOT EMPTY . USE THIS FUNCTION */
	public static boolean deleteNon_EmptyDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteNon_EmptyDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	    return dir.delete();
	}
}

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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv"
    />
<Button
	android:text="Delete Directory"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Now go to File-explorer in the window menu->show View and see the result.

After directory creation.

After directory deletion.

How to create a text file in C# ?

Hi,

How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter yourStream= null;
    string yourString= "I Love Coderz Heaven!";

    try
    {
      yourStream = File.CreateText("testFile.txt");
      yourStream.Write(yourString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (yourStream!= null)
      {
          yourStream.Close();
      }
    }
  }
}

:)

A simple exception handling using C#

Hi,

See how a very simple exception handling works with try-catch methods using C#.

using System;

class MainClass{

    public static void Main(){

        int divOne = 0;

        try {
            int ans = 79 / divOne ;
        }

        catch (Exception e) {
            Console.WriteLine("You got the exception-> " + e.Message);
        }

    }
}

Output- “You got the exception-> Attempted to divide by zero.”
:)

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/

Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.

Hi all……

Here is a simple example of expandandable ListView in ANDROID.
But I am not going to explain any code, because everything is explained inside the java file.
Make sure to read it.

Expandable ListView

package pack.Coderzheaven;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;

public class ExpandableListDemo extends ExpandableListActivity {

	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
    	try{
    		 super.onCreate(savedInstanceState);
    		 setContentView(R.layout.main);

        SimpleExpandableListAdapter expListAdapter =
			new SimpleExpandableListAdapter(
					this,
					createGroupList(), 				// Creating group List.
					R.layout.group_row,				// Group item layout XML.
					new String[] { "Group Item" },	// the key of group item.
					new int[] { R.id.row_name },	// ID of each group item.-Data under the key goes into this TextView.
					createChildList(),				// childData describes second-level entries.
					R.layout.child_row,				// Layout for sub-level entries(second level).
					new String[] {"Sub Item"},		// Keys in childData maps to display.
					new int[] { R.id.grp_child}		// Data under the keys above go into these TextViews.
				);
			setListAdapter( expListAdapter );		// setting the adapter in the list.

    	}catch(Exception e){
    		System.out.println("Errrr +++ " + e.getMessage());
    	}
    }

	/* Creating the Hashmap for the row */
	@SuppressWarnings("unchecked")
	private List createGroupList() {
	  	  ArrayList result = new ArrayList();
	  	  for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
	  		HashMap m = new HashMap();
	  	    m.put( "Group Item","Group Item " + i ); // the key and it's value.
	  		result.add( m );
	  	  }
	  	  return (List)result;
    }

	/* creatin the HashMap for the children */
    @SuppressWarnings("unchecked")
	private List createChildList() {

    	ArrayList result = new ArrayList();
    	for( int i = 0 ; i < 15 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
    	  /* each group need each HashMap-Here for each group we have 3 subgroups */
    	  ArrayList secList = new ArrayList();
    	  for( int n = 0 ; n < 3 ; n++ ) {
    	    HashMap child = new HashMap();
    		child.put( "Sub Item", "Sub Item " + n );
    		secList.add( child );
    	  }
    	 result.add( secList );
    	}
    	return result;
    }
    public void  onContentChanged  () {
    	System.out.println("onContentChanged");
	    super.onContentChanged();
    }
    /* This function is called on each child click */
    public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
    	System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
    	return true;
    }

    /* This function is called on expansion of the group */
    public void  onGroupExpand  (int groupPosition) {
    	try{
    		 System.out.println("Group exapanding Listener => groupPosition = " + groupPosition);
    	}catch(Exception e){
    		System.out.println(" groupPosition Errrr +++ " + e.getMessage());
    	}
    }
}

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"
    >
 <ExpandableListView android:id="@+id/android:list"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:background="@drawable/bkg"/>

     <TextView android:id="@+id/android:empty"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:text="No items"/>
</LinearLayout>

The child_row.xml

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

    <TextView android:id="@+id/grp_child"
         android:paddingLeft="50px"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="normal"
         android:layout_width="150px"
         android:layout_height="wrap_content"/>

</LinearLayout>

The group_row.xml

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

    <TextView android:id="@+id/row_name"
         android:paddingLeft="50px"
         android:textSize="20px"
         android:textColor="@drawable/blue"
         android:textStyle="normal"
         android:layout_width="320px"
         android:layout_height="wrap_content"/>

</LinearLayout>

The strings.xml (This file contains the string for the color that is used for text in the ListView)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExpandableList Demo</string>
    <drawable name="white">#ffffff</drawable>
	<drawable name="blue">#2554C7</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="orange">#ff9900</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="gray">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
</resources>

The manifest.xml

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

Please leave your comments if the post was useful.
Follow me on facebook, twitter and google plus for more updates.

Download.

How to read a folder in the assets directory and read files from it in android?

File reading is important in android. For the put the files in the assets folder.

We can able to read

  • foldername
  • filename
  • Contents of the file

First we read the name of the folder.

private String folder_array[];
AssetManager mngr_spinner = getAssets();
try
{
         //"air" is the name of the folder...
	folder_array= mngr_spinner.list("air");
}
catch (IOException e1)
{
	e1.printStackTrace();
}

“folder_array” contains all the names of the folder
Then if the path is set to

folder_array= mngr_spinner.list("air/Buttons Events");

Then the list of file name is got.
If you want to read the file content then do the following..

InputStream is;
try
{
	is = getAssets().open(air/Buttons Events/filename);
	int siz = is.available();
	byte[] buffer = new byte[siz];
	is.read(buffer);
        //This text contains the content of the file..
	String text = new String(buffer);
        is.close();
}
catch (Exception e)
{
	 Toast.makeText(CheatSheet.this,"File Not Found Error.Please ensure that file is not deleted.", Toast.LENGTH_SHORT).show();
}

Creating Exceptions in JAVA

This is a simple custom exception in java. That is, we can create an exception by extending the exception class.

The “throw new MyExcep” will throw an exception and the error message we specified will be displayed

import java.lang.Exception;
@SuppressWarnings("serial")
class MyExcep extends Exception
{
	MyExcep(String Errormsg)
	{
		super(Errormsg);	// call Exception class error message
	}
}
public class Example
{
	public static void main(String[] args)
	{
		int x = 5 , y = 1000;
		try
		{
			float z = (float) x / (float) y;
			if(z < .01)
			{
				throw new MyExcep("Number is too small");
			}
		}
		catch(MyExcep e)
		{
			System.out.println("Caught My Exception");
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("I am Always Here");
		}
	}
}

The output will be like this

Caught My Exception
Number is too small
I am Always Here

How to use MediaPlayer in ANDROID? A simple example.

MediaPlayer class can be used to play Audio in ANDROID.
See how to do this.

MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(MyClassName.this,songId);
		try {
			mp.prepare();

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (Exception e) {
			Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();			}
		mp.start();

        //Called when the song completes.....
            mp.setOnCompletionListener(new OnCompletionListener() {
  			public void onCompletion(MediaPlayer mp) {
  			}
  		});

Java Exception

Simple java program to show how exception works

public class exception
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 10/0;
}
catch(ArithmeticException e)
{
System.out.println(“Exception Caught ” + e);
}
}
}
The output will be like you expect
Exception Caught java.lang.ArithmeticException: / by zero

Dynamically Load images in ANDROID? OR Load image in ANDROID using a string path.

With the following code you can load images in your drawable folder dynamically by giving the filename as a String. For that you have to use getResources().getIdentifier which has parameters as the “path”,”drawable” and the “package name”. This returns a unique resource ID which can be used to set the image for a ImageView using

imageView.setImageResource(imgID);

public void changeImage(String path)
{
    try
    {
          int imgID = getResources().getIdentifier(path, "drawable",
                        "your_package_name_here");
          imageView.setImageResource(imgID);
    }
    catch(Exception e)
    {
         Toast.makeText(MyActivity.this,e.getMessage() + "Error : ",
         Toast.LENGTH_SHORT).show();
    }
}

Play all songs from your raw directory in ANDROID continuously.

In ANDROID all resource has a unique resource ID which we get by passing the song name to the function below playSong().

The function getAllResourceIDs() will convert this String which is the name of the song to the unique resource ID which can then be used to play the song.

setOnCompletionListener() will be executed when the MediaPlayer completes playing a song with in which you can call this function again with next song parameter to play the next song.

public int songId = 0;
public void playSong(String to_play_song)
{
       songId = getAllResourceIDs(R.raw.class, to_play_song);
       mp = MediaPlayer.create(geetaact.this,songId);
       try
       {
               mp.prepare();
       }
       catch (IllegalStateException e) {
                  e.printStackTrace();
       } catch (Exception e) {
                 e.printStackTrace();
       }
       mp.start();

       //Called when the song completes.....
      mp.setOnCompletionListener(new OnCompletionListener()
      {
	      public void onCompletion(MediaPlayer mp)
	      {
	            //Get next song and play again continuosly.
	     }
	  );
}

//function which returns the unique resource ID.
public static int getAllResourceIDs(Class c, String song) throws IllegalArgumentException
{
           //System.out.println("inside HashMap"+ song);
       HashMap resmap = new HashMap();
       java.lang.reflect.Field[] fields = c.getFields();
       try
       {
               for(int i = 0; i < fields.length; i++)
               {
	               if(song != null)
	                     if(fields[i].getName().startsWith(song))
	                        resmap.put(fields[i].getName(), fields[i].getInt(null));
	                else
	                     resmap.put(fields[i].getName(), fields[i].getInt(null));
               }
       } catch (Exception e)
       {
                  throw new IllegalArgumentException();
       }
       Integer one = (Integer) resmap.get(song);
       int songid = one.intValue();
       return songid;
   }
}