Saturday, 21 January 2012

MilliSecond to HH:MM:SS format convertor

All thanks to Stack overflow post complete function to get HH:MM:SS format for given time in millisecond.
private String formatTime(long millis) {

            String output = "00:00:00";

            long seconds = millis / 1000;

            long minutes = seconds / 60;

            long hours = minutes / 60;

 

            seconds = seconds % 60;

            minutes = minutes % 60;

            hours = hours % 60;

 

            String secondsD = String.valueOf(seconds);

            String minutesD = String.valueOf(minutes);

            String hoursD = String.valueOf(hours);

 

            if (seconds < 10)

                  secondsD = "0" + seconds;

            if (minutes < 10)

                  minutesD = "0" + minutes;

            if (hours < 10)

                  hoursD = "0" + hours;

 

            output = hoursD + " : " + minutesD + " : " + secondsD;

            return output;

      }

Monday, 14 November 2011

Copy database from assets to local memory

I needed to copy the assests databse to be in local memory i just came around some links with help of that code i done few code changes to work it properly cheers!!

public class DataBaseHelper extends SQLiteOpenHelper {

 //The Android's default system path of your application database.
 private static String DB_PATH = "/data/data/PACKAGENAME/databases/";

 private static String DB_NAME = "myDB.db";
 
 private final String DB_Internal = "myDB";

 private SQLiteDatabase myDataBase; 

 private final Context myContext;

 /**
  * Constructor
  * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
  * @param context
  */
 public DataBaseHelper(final Context context) {
  super(context, DB_NAME, null, 1);
  this.myContext = context;
 } 

 /**
  * Creates a empty database on the system and rewrites it with your own database.
  * */
 public final void createDataBase() throws IOException {

  final boolean dbExist = checkDataBase();
  SQLiteDatabase db_Read = null;
  if (dbExist) {
   //do nothing - database already exist
  } else {
   //By calling this method and empty database will be created into the default system path
   //of your application so we are gonna be able to overwrite that database with our database.
   //By calling this method and empty database will be created into the default system path 
   //of your application so we are gonna be able to overwrite that database with our database. 
   db_Read = this.getReadableDatabase(DB_Internal); 
   db_Read.close();
   try {
    copyDataBase();
   } catch (IOException e) {
    throw new Error("Error copying database");
   }
  }
 }

 /**
  * Check if the database already exist to avoid re-copying the file each time you open the application.
  * @return true if it exists, false if it doesn't
  */
 private boolean checkDataBase() {
  final File dbFile = new File(DB_PATH + DB_NAME);
  return dbFile.exists();
 }

 /**
  * Copies your database from your local assets-folder to the just created empty database in the
  * system folder, from where it can be accessed and handled.
  * This is done by transfering bytestream.
  * */
 private void copyDataBase() throws IOException {

  //Open your local db as the input stream
  final InputStream myInput = myContext.getAssets().open(DB_NAME);

  // Path to the just created empty db
  final String outFileName = DB_PATH + DB_NAME;

  //Open the empty db as the output stream
  final OutputStream myOutput = new FileOutputStream(outFileName);

  //transfer bytes from the inputfile to the outputfile
  final byte[] buffer = new byte[1024];
  int length;
  while ((length = myInput.read(buffer)) > 0) {
   myOutput.write(buffer, 0, length);
  }

  //Close the streams
  myOutput.flush();
  myOutput.close();
  myInput.close();

 }

 public final void openDataBase() throws Exception {
  //Open the database
  final String myPath = DB_PATH + DB_NAME;
     myDataBase = SQLiteDatabase.openDatabase(myPath, DB_Internal, null, SQLiteDatabase.OPEN_READONLY);
 }

 @Override
 public final synchronized void close() {
  if (myDataBase != null)
   myDataBase.close();
  super.close();
 }

 @Override
 public void onCreate(final SQLiteDatabase arg0) {
 }

 @Override
 public void onUpgrade(final SQLiteDatabase arg0, final int arg1, final int arg2) {
 }
}

Wednesday, 9 November 2011

Swipe event in android ScrollView

If your Layout have scroll view then its difficult to detect the swipe event into scroll view using Gesture detector. After following several solutions and looking on stack overflow I made some changes which work great in detecting swipe in scroll view. If you use Gesture and override touch event you will be able to detect event but the scollview scroll will not work so try this solution.
import android.app.Activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;

public class ActivitySwipeDetector implements View.OnTouchListener {

 private Activity activity;
 static final int MIN_DISTANCE = 100;
 private float downX, downY, upX, upY;

 public ActivitySwipeDetector(final Activity activity) { 
  this.activity = activity;
 }

 public final void onRightToLeftSwipe() {
  Log.i("RightToLeftSwipe!");
 }

 public void onLeftToRightSwipe(){
  Log.i( "LeftToRightSwipe!");
 }

 public void onTopToBottomSwipe(){
  Log.i( "onTopToBottomSwipe!");
 }

 public void onBottomToTopSwipe(){
  Log.i( "onBottomToTopSwipe!");
 }

 public boolean onTouch(View v, MotionEvent event) {
  switch(event.getAction()){
  case MotionEvent.ACTION_DOWN: {
   downX = event.getX();
   downY = event.getY();
   //   return true;
  }
  case MotionEvent.ACTION_UP: {
   upX = event.getX();
   upY = event.getY();

   float deltaX = downX - upX;
   float deltaY = downY - upY;

   // swipe horizontal?
   if(Math.abs(deltaX) > MIN_DISTANCE){
    // left or right
    if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
    if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
   } else { Log.i( "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); }

   // swipe vertical?
   if(Math.abs(deltaY) > MIN_DISTANCE){
    // top or down
    if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
    if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
   } else { Log.i( "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); }

   //     return true;
  }
  }
  return false;
 }
}

Saturday, 20 August 2011

How to create Sqlite databse in sdcard

I was looking for the proper solution for creating database in sdcard android after many crashes and links i made the code.

package com.android.database;

import java.io.File;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class DatabaseHelper

{
	private static final String TAG  = "DatabaseHelper";
	public static final String  DATABASE_FILE_PATH = "/sdcard";
	public static final String  DATABASE_NAME = "testDatabase";

	private static final String TRACKS_TABLE_CREATE =
		"create table if not exists casecategory (_id INTEGER primary key autoincrement, "
		+ "category_name TEXT not null);";
	
	private SQLiteDatabase database;
	
	public DatabaseHelper()
	{  
		try
		{
//			database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH + File.separator + DATABASE_NAME, null,SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
			database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FILE_PATH + File.separator + DATABASE_NAME, null);
			createTables();
		}

		catch (SQLiteException ex)
		{
//			createTables();
			Log.e(TAG, "error -- " + ex.getMessage(), ex);
		}
		finally
		{
			DatabaseUtil.closeDataBase(database);
		}
	}

	private void createTables()
	{
		try {
			database.execSQL(TRACKS_TABLE_CREATE);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close()
	{
		DatabaseUtil.closeDataBase(database);
	}

	public SQLiteDatabase getReadableDatabase()
	{
		database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH

				+ File.separator + DATABASE_NAME, null,

				SQLiteDatabase.OPEN_READONLY);
		return database;
	}

	public SQLiteDatabase getWritableDatabase()
	{
		database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH

				+ File.separator + DATABASE_NAME, null,

				SQLiteDatabase.OPEN_READWRITE);

		return database;
	}
}


package com.android.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseUtil
{
	public static void closeCursor(Cursor cursor)
	{
		if (cursor != null)
		{
			cursor.close();
		}
	}

	public static void closeDataBase(SQLiteDatabase database)
	{
		if (database != null)
		{
			database.close();
		}
	}
}



package com.android.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter {

	private DatabaseHelper databaseHelper;
	private SQLiteDatabase database;
	
	public DBAdapter open() throws Exception{
		databaseHelper = new DatabaseHelper();
		database = databaseHelper.getWritableDatabase();
		return this;
	}
	
	public boolean insertIntoTable(){
		try {
			database.execSQL("insert into casecategory values('5','v2');");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public Cursor getData(){
		return database.rawQuery("select _id,category_name from casecategory;", null);
	}
	
	public void close() throws Exception{
		database.close();
	}
	
}



package com.android.sdcardDatabase;

import com.android.database.DBAdapter;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;

public class SdCardDatabaseActivity extends Activity {

	/** Called when the activity is first created. */

	DBAdapter dbAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		dbAdapter = new DBAdapter();
		try {
			dbAdapter.open();
		} catch (Exception e) {
			e.printStackTrace();
		}

		setContentView(R.layout.main);
		//		
		boolean flag = dbAdapter.insertIntoTable();
		if(flag==true){
			Toast.makeText(this,"True  ",Toast.LENGTH_LONG).show();
		}else{
			Toast.makeText(this,"False  ",Toast.LENGTH_LONG).show();
		}



		Cursor c = dbAdapter.getData();
		if (c != null ) {
			if  (c.moveToFirst()) {
				do {
					String firstName = c.getString(c.getColumnIndex("category_name"));
					System.out.println("fir ::"+firstName);
				}while (c.moveToNext());
			} 
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			dbAdapter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

Friday, 29 July 2011

Spinner with SimpleCursorAdapter Android

If you are using android sqlite database and you want to set query data base to set in spinner on list view than you can use the SimpleCursorAdapter.

Advantage of using the SimpleCursorAdapter that when you implement on click listener on onItemSelectedListner than you don't have to save query database locally in array or something.

Cursor cursor = dbAdapter.getAllData();

  if(cursor.getCount()>0){
   String[] from = new String[]{"columm_name"};
   // create an array of the display item we want to bind our data to
   int[] to = new int[]{android.R.id.text1};
   SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item,
     cursor, from, to);
   mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
   spinnerName.setAdapter(mAdapter);
  }
 

Now implementing all click listner and query the selected item id or other columm data from database.

spinnerName.setOnItemSelectedListener(new OnItemSelectedListener() {

   public void onItemSelected(AdapterView parent, View view,
     int pos, long log) {
    
    Cursor c = (Cursor)parent.getItemAtPosition(pos);
          int id = c.getInt(c.getColumnIndexOrThrow("columm_name")); 
   }

   public void onNothingSelected(AdapterView arg0) {
    
   }
  });

Tuesday, 24 May 2011

Showing Dialog On Home screen Android


Today i was working for my application and i wanted to show the dialog on home screen as my widget get update of news. As widget updted method was inside the broadcast receiver i was not able to show the dialog i was getting view not attached error as no view there to attach window, So the solution for that is to start the activity from your broadcast receiver. and give the activity a android dialog theme inside manifest.

like this



Saturday, 21 May 2011

Google I/O 2011 whts New ?

This time in Google keynote the day one was all focused on android. The amazing accessories hardware was shown seems like they are looking forward to focus more on android hardware accessories.

some of the announcement made at Google I/O.


  • Honeycomb 3.1 update coming to tablets.
  • Android next version Ice cream sandhwich com pitiable to tablet and device will be easy for developers.
  • Open Hardware accessories.
  • Galaxy special I/O addition tablet given free to the developers at Google I/O Event.
  • Google Music Beta for all platforms cloud music.
  • Movie app for android phone and tablets and Movie rental system.
  • Next day it was focused on chrome chrome app store and chrome OS notebooks.


Techin Android

Techin Android Developer