ExtJS: Horizontal sliding style paging for long panel [part-2]

In Part-1 I showed how we can use scrollBy(). In this part-2 we will see how we can do it with Position.

Panel Settings as before:

Ext.define('MyProj.view.AllPacksPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.allpackspanel',
    title: 'All Packs',
    layout: 'hbox',
    id: 'allpackspanel',  //this is the ID we will use to get the component in button handler
    overflowX: 'scroll',  //horizontal scroll will be shown
    ...
    ...

Button with handler.

	dockedItems: [{
        xtype: 'toolbar',
        dock:'bottom',
        ui: 'footer',
        items: [
        {
            text: 'prev'
           iconCls: 'icon-prev'
           handler: function() {
               var cmp = Ext.getCmp("allpackspanel");
               var pos = cmp.getPosition();
               cmp.setPosition(pos[0]+300,pos[1],true);
           }
        },
        '->',
        {
            text: 'next'
           iconCls: 'icon-next'
           handler: function() {
               var cmp = Ext.getCmp("allpackspanel");
               var pos = cmp.getPosition();
               cmp.setPosition(pos[0]-300,pos[1],true);
           }
        }
        ]
    }]

The difference with scrollBy() in nothing at all. You may be noticed that both of this have the scroll bar is visible. If we Disable the scroll bar then this function will have no effect. But, seeing scroll bar is annoying. So We will see in Horizontal sliding style paging using jQuery how we can hide the scroll bar and make a smooth sliding like this.

ExtJS: Horizontal sliding style paging for long panel [part-1]

There are several ways to achieve Horizontal sliding style paging for a panel which is horizontally larger than window. Here in part-1 I will show how to use scrollBy() . For my case there are more than 20 Grid panel was added in a Panel. FYI: I used the MVC architecture of ExtJS.

I have added two button at bottom (Next and Prev) to move the scroll. So the code was like bellow:

Panel settings was:

Ext.define('MyProj.view.AllPacksPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.allpackspanel',
    title: 'All Packs',
    layout: 'hbox',
    id: 'allpackspanel',  //this is the ID we will use to get the component in button handler
    overflowX: 'scroll',  //horizontal scroll will be shown
    ...
    ...

And code for button with handler:

    dockedItems: [{
        xtype: 'toolbar',
        dock:'bottom',
        ui: 'footer',
        items: [
        {
            text: 'prev'
           iconCls: 'icon-prev'
           handler: function() {
               var cmp = Ext.getCmp("allpackspanel");
               cmp.scrollBy(-300,0,true);
           }
        },
        '->',
        {
            text: 'next'
           iconCls: 'icon-next'
           handler: function() {
               var cmp = Ext.getCmp("allpackspanel");
               cmp.scrollBy(300,0,true);  //300 as I want it will scroll by inner inner grid where inner grid panel size is 300
           }
        }
        ]
    }]

We will see in Part-2 how we can do the same with the position.

How to use the “tilt” feature on an iphone

You can do this by accelerometer. Accelerometer will give you the value for x y z axis value when you tilt the device. to this add a property which is type of UIAccelerometer class.

    UIAccelerometer*  theAccelerometer;
	

now you define the frequency and the delegate. you should write this code from where you want to initiate receiving.

    theAccelerometer = [UIAccelerometer sharedAccelerometer];
    theAccelerometer.updateInterval = 1 / 50;
    theAccelerometer.delegate = self;
	

Now you have to add the delegation method

    -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
        myX = acceleration.x;
        myY = acceleration.y;
        myZ = acceleration.z;
    }
	

Ok, now you have the value updated frequently at frequency 50 [means 20 mili second]. Now, if you want to stop receiving these values and obviously you should stop receiving if you leave this view and that will as follows:

    theAccelerometer.delegate = nil
	

Again you can start receiving accelerometer data again assigning the delegate to self

    theAccelerometer.delegate = self;
	

if you have any further question please feel free to contact.

Objective-C and sqlite’s DATETIME type

Well, I am sharing here just the core things regarding date formatting for saving and retrieving the data from Sqlite to Objective C or vice versa. If you have any problem with this code snippet then I will share the full code that I used for my project.

When you save your data, bind your date value in the sql statement like this way:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString=[dateFormat stringFromDate:[NSDate date];];

    sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);
	

and when you retrieve data you have to write this code:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];
	

now you have a variable myDate of NSDate type which you can render in your way:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
    NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);
	

You must have to remember 3 things:

  1. in your SQLite date field type should be DATETIME
  2. Date format should be same when you store and when you retrieve
  3. Now you can show in your won way but following the format. Bellow the format details has given.

Format:

    'dd' = Day 01-31
   'MM' = Month 01-12
   'yyyy' = Year 2000
   'HH' = Hour in 24 hour
   'hh' = Hour in 12 hour
   'mm' = Minute 00-59
   'ss' = Second 00-59
   'a' = AM / PM

SQLite Database in Android: how to

Well, we will see here today how to use SQLite Database in Android Application. In Android there are some libraries to handle or use SQLite Database. SQLite Database basically a file where everything stored, database schema, structures and data. There is no server or a different tier for handling the DBMS.

OK, Now we see how to add a db to android application. Basically, in Android there is a helper which will act like a bridge or the connector for your database and its tables. So first we have to create the helper for our database. For say, our db name is “LibraryDB”. So we will create the helper as:

	public class LibraryDB  extends SQLiteOpenHelper{
		....
		....
	}

The heper class “SQLiteOpenHelper” is an abstract class. So we must have to implement the constructor. The constructor is like –

public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

name is the name of the Database and version is the version of your database. It will handle changing your database schema version in future when we will release our next version of this application. For avoiding confusion this is not the SQLite Version. So we will implement the constructor as:

	public LibraryDB(Context context) {
		super(context, LibraryDB.class.getSimpleName(), null, 1);
	}

Here LibraryDB.class.getSimpleName() returns the simple name of the class. So the database name will be the same name of our Helper class name. We can give a different name here. And our DB version is 1 for this scenario.

Now we have to override and implement two methods, are onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int oldVersion, int currentVersion). The onCreate method are called when first time the helper is called. when the database has been created and in constructor new version number has given or the version number doesn’t match the existing current db then it will call the onUpgrade method. So we will handle this in such way where we can apply new schema by changing version number in connector.

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "";// the sql query for creating the tables
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if(oldVersion == 1){
			//write code for altering from version 1 to 2

			//and then call recursively increasing old version and handle that in the next logic and so on
			this.onUpgrade( db, ++oldVersion, newVersion);
		}
		else if(oldVersion == 2){
			//write code for altering from version 2 to 3

			//and then call recursively increasing old version and handle that in the next logic and so on
			this.onUpgrade( db, ++oldVersion, newVersion);
		}
		//....
		//....
	}

So our Connector, database and tables has been created. Now we need to insert the data and retrieve the data. So, we will see the insertion operations.

	LibraryDB dbCon = new LibraryDB(this);
	SQLiteDatabase dbw = dbCon.getWritableDatabase();  // to do write operations like insert, update and delete we have to connect trough this method

	//for name value pare we will use ContentValues object
	ContentValues values = new ContentValues();

	// now put the data to insert
	values.put("name", "the name value");
	values.put("section", "section id");
	//...

	// now inset the data
	dbw.insert("user", null, values);

	//now close the db
	dbw.close();

To insert data we used insert(String table, String nullColumnHack, ContentValues values) method, we also can use insertOrThrow(String table, String nullColumnHack, ContentValues values) method.

To update update(String table, ContentValues values, String whereClause, String[] whereArgs) and to delete delete(String table, String whereClause, String[] whereArgs) method but the same way that used for insertion operation.

This also supports Transactions.

	db.beginTransaction();
	try {
	 //do operations
	 //...
	 //...
	 db.setTransactionSuccessful();
	} finally {
	 db.endTransaction();
	}

We saw how to open the DB as writable, now we will see how to open as readable and how to get the data from the db.

To open the DB as readable we will call the getReadableDatabase() method on the connection.

	SQLiteDatabase dbr = dbCon.getReadableDatabase();
	Cursor cursor = dbr.query("user", null, null, null, null, null, "name DESC");

	startManagingCursor(cursor); //start handling cursors

	while (cursor.moveToNext()){ // runs the loop only when cursor can move to next data
		name = cursor.getString(cursor.getColumnIndex("name"));
		// do the required action with the data
	}

To get the data we use the query method which is – query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) and it returns a cursor object with found data.

For more information please refer to : http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

Feel free to contact for any necessary…
Hussain Behestee
or email here.

How to switch between screens with data in android

Hi
Here we will see some tricks and techniques for switching between Screen in Android. For 1st example I consider you have two activity name FisrtActivity.java and SecondActivity.java

First activity have a button and on clicking that the screen will switch to SecondActivity. so the code will be for this:

    Intent nextScreen = new Intent(getApplicationContext(), 
        SecondActivity.class);
    startActivity(nextScreen);

So this code is loading the second screen on click, so the full code should look like this:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // This is the layout for the first screen. File should place 
        // in layout folder named firstscreen.xml (considering you 
        // know how to create a layout, If not please find my another 
        // article for that..)
        setContentView(R.layout.firstscreen);  

        Button goToSecScreen = (Button) findViewById(
               R.id.btnGoToSecScreen);
        goToSecScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View arg0) {
                //Starting a new Activity
                startActivity(new Intent(getApplicationContext(), 
                      SecondActivity.class));
 
            }
        });

For next examples I am considering that you will be able to handle the on click part. Ok now we will see how to send data to second activity:

Btw, the following code

    startActivity(new Intent(getApplicationContext(), 
         SecondActivity.class));

can be written as bellow:

    Intent secondScreen = new Intent(getApplicationContext(), 
           SecondActivity.class);
    startActivity(secondScreen );

These tow lines does the same thing as above.

So now, we will send some data to the second activity. so first activity code will be like this:

    Intent secondScreen = new Intent(getApplicationContext(), 
           SecondActivity.class);
    
    //adding data to the intent to send to second screen as well
    secondScreen .putExtra("name", "my name");
    // this code if you have text field associated this var inputName
    /*secondScreen .putExtra("name", inputName.getText().toString());*/

    secondScreen .putExtra("email", "my email");
    // this code if you have text field associated this var inputEmail
    /*secondScreen .putExtra("email", inputEmail.getText().toString());*/

    startActivity(secondScreen );

So, it sends the data to second screen, now we have to catch the data. so the following code have to write in onCreate method in SecondActivity.java file:

    Intent firstScreen = getIntent();
    
    // Receiving the Data
    String name = firstScreen.getStringExtra("name");
    String email = firstScreen.getStringExtra("email");
    Log.e("Second Screen", name + "." + email);
 
    // Displaying Received data, assuming you have these two text field in second screen
    //txtName.setText(name);
    //txtEmail.setText(email);

So, if my case is I also want that the second activity also will some data to the first screen then just wirte in the FirstActivity as

    // 2 is the which will be mention in result
    startActivityForResult(intent, 2);  

instead of

    startActivity(secondScreen );

override the implementation of “onActivityResult()” method. So in FirstActivity should have this code:

    @Override
    protected void onActivityResult(int requestCode, 
              int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 2 is the same ocde that you send to the second 
        // screen when loading..
        if(requestCode == 2){  
 
            // Receiving the Data
            String name = data.getExtras().get("name");
            String mail = data.getExtras().get("mail");
            Log.e("First Screen", name + "." + mail);
 
            // Displaying Received data, assuming you have these 
            // two text field in first screen
            //txtName.setText(name);
            //txtEmail.setText(mail);
        }
 
    }

and the second screen should have this code in the button click to response the result to the first screen

    Intent firstScreen = getIntent();
    firstScreen.putExtra("name", "AndroidHive.info");
    // this code if you have text field associated this 
    // var inputName
    /*firstScreen.putExtra("name", 
           inputName.getText().toString());*/

    firstScreen.putExtra("email", "AndroidHive.info");
    // this code if you have text field associated this
    // var inputEmail
    /*firstScreen.putExtra("mail", 
           inputEmail.getText().toString()); */ 

    // Setting resultCode to 2 to identify on old activity
    setResult(2,firstScreen);

    // now close the second screen
    finish();

So? what we have seen? for just load an activity we will call startActivity(). For getting data back from the loaded activity we will call startActivityForResult() with result code to identify this result came from which call and will override and implement onActivityResult() method. In this case we will hust call the finish() method to return back to the caller Activity.

I Hope you will be able to write down the full code. If not then please fork this from github: https://github.com/behestee/ActivityInteraction

Add infoWindow for multiple marker in google map V3

How to add infoWindow as dynamic on multiple maker? I have tried in
lots of way and then I found that solution as given below:

function initialize() {

    var locations = [ [ 'Bondi Beach', -33.890542, 151.274856 ],
            [ 'Coogee Beach', -33.923036, 151.259052 ],
            [ 'Cronulla Beach', -34.028249, 151.157507 ],
            [ 'Manly Beach', -33.80010128657071, 151.28747820854187 ],
            [ 'Maroubra Beach', -33.950198, 151.259302 ] ];

    var latlng = new google.maps.LatLng(-33.890542, 151.274856);

    var settings = {
        zoom : 10,
        center : latlng,
        mapTypeControl : true,
        mapTypeControlOptions : {
            style : google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        navigationControl : true,
        navigationControlOptions : {
            style : google.maps.NavigationControlStyle.SMALL
        },
        mapTypeId : google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("mapContainer"),
            settings);

    var companyLogo = new google.maps.MarkerImage("parking.png",
            new google.maps.Size(100, 50), new google.maps.Point(0, 0),
            new google.maps.Point(50, 50));
    var companyShadow = new google.maps.MarkerImage("parking_shadow.png",
            new google.maps.Size(130, 50), new google.maps.Point(0, 0),
            new google.maps.Point(65, 50));
    var companyMarker = [];
    var infowindow = [];
    var loc = null;
    var myLatLng = null;
    for ( var i = 0; i < locations.length; i++) {

        loc = locations[i];
        myLatLng = new google.maps.LatLng(loc[1], loc[2]);
        eval("var companyMarker"
                + i
                + " = new google.maps.Marker({ position: myLatLng, map: map, icon: companyLogo, shadow: companyShadow, title:loc[0],zIndex: i});");
    }
    var a = [];
    for (i = 0; i < locations.length; i++) {

        google.maps.event
                .addListener(
                        eval("companyMarker" + i),
                        'click',
                        function() {
                            var ind = $(this).attr('z-index');
                            if (infowindow[ind])
                                infowindow[ind].close();
                            eval("var infowindow"
                                    + ind
                                    + " = new google.maps.InfoWindow({content: locations[ind][0]});");
                            eval("infowindow" + ind).open(map,
                                    eval("companyMarker" + ind));
                        });
    }
}

$(document).ready(function() {
    initialize();
});

If there anything seems confusing feel free to contact me.

Regular expression for URL validation

Some times we may need to validate the URL from back-end or front-end.

I used following codes and works good for me. You can check it once if you need.

So for PHP

    function is_valid_url($url) {
        return preg_match('/^((ht|f)tp(s?)(:\/\/))?([a-z0-9-]+[.]{1})+[a-z0-9-]+(:[0-9]*)?(\/{1}[a-zA-Z0-9\-\.\?\,\:\!\'\/\\\+&%\$#_=]+)*\/?$/i', $url);
    }

And for JS

    function is_valid_url(url) {
        var urlregex = new RegExp(/^((ht|f)tp(s?)(:\/\/))?([a-z0-9-]+[.]{1})+[a-z0-9-]+(:[0-9]*)?(\/{1}[a-zA-Z0-9\-\.\?\,\:\!\'\/\\\+&%\$#_=]+)*\/?$/i);
        return urlregex.test(url);
    }

This will allow following pattern of URL
http://www.abc.com
http://www.abc.com:8080
http://www.abc.com:8080/abc.xyz?a=2&b:c#!landingpage
https://www.abc.com
http://www.abc.com
http://www.abc.com/path/
http://www.yahoo.com/path/to

Geo Proximity Search in Large Database

I was creating an application with Geo Proximity Search capability
using PHP as server scripting language and MySQL as Database.

I got the solution that might help you.

If we have certain set of objects having their latitude and longitude, we can find some locations from my database with an specified location along with range/radius in KM we are using MySQL Query. Bellow is the given query where [table] means the storage where my all locations are stored and [latitude], [longitude]  are the specified location with whom we are going to compare.

SELECT [columns] FROM [table] WHERE 1=1 AND 3963.191 * ACOS((SIN(PI
() * [latitude] / 180) * SIN(PI() * [table].latitude / 180)) + (COS(PI
() * [latitude] /180) * cos(PI() * [table].latitude / 180) * COS(PI()
* [table].longitude / 180 - PI() * [longitude] / 180)) ) <= 15

Above calculations will give the objects that are within the 15 KM
area from the searched location’s center.

How to get visitors IP address in PHP

Hi, This is very simple thing, but might helpful for beginners. So bellow are the different codes for getting visitors IP address.

//Globals off work round
if (!ini_get('register_globals')) {
    $reg_globals = array($_POST, $_GET, $_FILES, $_ENV, $_SERVER, $_COOKIE);
    if (isset($_SESSION)) {
        array_unshift($reg_globals, $_SESSION);
    }
    foreach ($reg_globals as $reg_global) {
        extract($reg_global, EXTR_SKIP);
    }
}

//Find the IP of the visitor

if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $rip = getenv("HTTP_CLIENT_IP");
} else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $rip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $rip = getenv("REMOTE_ADDR");
} else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $rip = $_SERVER['REMOTE_ADDR'];
} else {
    $rip = "unknown";
}

//Display the IP of the Visitor

echo "Your IP is $ip";

If there any confusion occurs then feel free to contact me..