Loading

Sunday, November 27, 2011

Implement Pinch Zoom in OnTouchListener

Modify the last exercise of "Implement OnTouchListener to handle multi-touch event" to implement our own pinch detection.

Implement Pinch Zoom in OnTouchListener

package com.exercise.AndroidTouchPinchZoom;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;

public class AndroidTouchPinchZoomActivity extends Activity {

TextView myTouchEvent;
ImageView myImageView;
Bitmap bitmap;
int bmpWidth, bmpHeight;

//Touch event related variables
int touchState;
final int IDLE = 0;
final int TOUCH = 1;
final int PINCH = 2;
float dist0, distCurrent;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myTouchEvent = (TextView)findViewById(R.id.touchevent);
myImageView = (ImageView)findViewById(R.id.imageview);

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
bmpWidth = bitmap.getWidth();
bmpHeight = bitmap.getHeight();

distCurrent = 1; //Dummy default distance
dist0 = 1; //Dummy default distance
drawMatrix();

myImageView.setOnTouchListener(MyOnTouchListener);
touchState = IDLE;
}

private void drawMatrix(){
float curScale = distCurrent/dist0;
if (curScale < 0.1){
curScale = 0.1f;
}

Bitmap resizedBitmap;
int newHeight = (int) (bmpHeight * curScale);
int newWidth = (int) (bmpWidth * curScale);
resizedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
myImageView.setImageBitmap(resizedBitmap);
}

OnTouchListener MyOnTouchListener
= new OnTouchListener(){

@Override
public boolean onTouch(View view, MotionEvent event) {
// TODO Auto-generated method stub

float distx, disty;

switch(event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
//A pressed gesture has started, the motion contains the initial starting location.
myTouchEvent.setText("ACTION_DOWN");
touchState = TOUCH;
break;
case MotionEvent.ACTION_POINTER_DOWN:
//A non-primary pointer has gone down.
myTouchEvent.setText("ACTION_POINTER_DOWN");
touchState = PINCH;

//Get the distance when the second pointer touch
distx = event.getX(0) - event.getX(1);
disty = event.getY(0) - event.getY(1);
dist0 = FloatMath.sqrt(distx * distx + disty * disty);

break;
case MotionEvent.ACTION_MOVE:
//A change has happened during a press gesture (between ACTION_DOWN and ACTION_UP).
myTouchEvent.setText("ACTION_MOVE");

if(touchState == PINCH){
//Get the current distance
distx = event.getX(0) - event.getX(1);
disty = event.getY(0) - event.getY(1);
distCurrent = FloatMath.sqrt(distx * distx + disty * disty);

drawMatrix();
}

break;
case MotionEvent.ACTION_UP:
//A pressed gesture has finished.
myTouchEvent.setText("ACTION_UP");
touchState = IDLE;
break;
case MotionEvent.ACTION_POINTER_UP:
//A non-primary pointer has gone up.
myTouchEvent.setText("ACTION_POINTER_UP");
touchState = TOUCH;
break;
}

return true;
}

};
}


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

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/touchevent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageview"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center" />

</LinearLayout>


Download the files.


Related article:
- Scale bitmap according to ScaleGestureDetector



Saturday, November 26, 2011

Connect to SQL Azure Using ADO.NET


Sample code using ADO.NET to connect to a database in Microsoft SQL Azure Database is very similar to connecting to an instance of SQL Server on your premises

Using this Example
To use this example in Visual Studio with your SQL Azure server, do the following steps:
  1. Open Visual Studio and create a new console application.
  2. Replace the code in the program file with the code from this example.
  3. Replace <ProvideUserName> with the name of an SQL Azure Database login that has been assigned the dbmanager role. Note: if you use the login@server username format, the server portion of the name must match the first part of the server's fully qualified name. For example, if your server is servername.database.windows.net, your login name will look like loginname@servername. For more information about SQL Azure Database roles.
  4. Replace <ProvidePassword> with the password associated with the login. Note: We recommend using a strong password when creating a login.
  5. Replace <ProvideServerName> with the fully qualified domain name of your SQL Azure server. For example: servername.database.windows.net
  6. Replace <ProvideDatabaseName> with the name of the database you want the code to create.
  7. Run the code.
' Sample Code
Option Explicit On
Option Strict On

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Data.SqlClient
Imports System.Data

Module Program
    ' Provide the following information
    Private ReadOnly userName As String = "<ProvideUserName>"
    Private ReadOnly password As String = "<ProvidePassword>"
    Private ReadOnly dataSource As String = "<ProvideServerName>"
    Private ReadOnly sampleDatabaseName As String = "<ProvideDatabaseName>"


    Sub Main()
        ' Create a connection string for the master database
        Dim connString1Builder As New SqlConnectionStringBuilder()
        With connString1Builder
            .DataSource = dataSource
            .InitialCatalog = "master"
            .Encrypt = True
            .TrustServerCertificate = False
            .UserID = userName
            .Password = password
        End With

        ' Create a connection string for the sample database
        Dim connString2Builder As New SqlConnectionStringBuilder()
        With connString2Builder
            .DataSource = dataSource
            .InitialCatalog = sampleDatabaseName
            .Encrypt = True
            .TrustServerCertificate = False
            .UserID = userName
            .Password = password
        End With


        ' Connect to the master database and create the sample database
        Using conn As New SqlConnection(connString1Builder.ToString())
            Using command As SqlCommand = conn.CreateCommand()
                conn.Open()

                ' Create the sample database
                Dim cmdText As String
                cmdText = String.Format("CREATE DATABASE {0}", _
                                        sampleDatabaseName)
                command.CommandText = cmdText
                command.ExecuteNonQuery()
                conn.Close()
            End Using
        End Using


        ' Connect to the sample database and perform various operations
        Using conn As New SqlConnection(connString2Builder.ToString())
            Using command As SqlCommand = conn.CreateCommand()
                conn.Open()

                ' Create a table
                command.CommandText = "CREATE TABLE T1(Col1 int primary key, Col2 varchar(20))"
                command.ExecuteNonQuery()

                ' Insert sample records
                command.CommandText = "INSERT INTO T1 (col1, col2) VALUES (1, 'string 1'), (2, 'string 2'), (3, 'string 3')"
                Dim rowsAdded As Integer = command.ExecuteNonQuery()

                ' Query the table and print the results
                command.CommandText = "SELECT * FROM T1"
                Using reader As SqlDataReader = command.ExecuteReader()
                    ' Loop over the results
                    While reader.Read()
                        Console.WriteLine("Col1: {0}, Col2: {1}", _
                                          reader("Col1").ToString().Trim(), _
                                          reader("Col2").ToString().Trim())
                    End While
                End Using

                ' Update a record
                command.CommandText = "UPDATE T1 SET Col2='string 1111' WHERE Col1=1"
                command.ExecuteNonQuery()

                ' Delete a record
                command.CommandText = "DELETE FROM T1 WHERE Col1=2"
                command.ExecuteNonQuery()

                ' Query the table and print the results
                Console.WriteLine("After update/delete, the table has these records...")
                command.CommandText = "SELECT * FROM T1"
                Using reader As SqlDataReader = command.ExecuteReader()
                    ' Loop over the results
                    While reader.Read()
                        Console.WriteLine("Col1: {0}, Col2: {1}", _
                                          reader("Col1").ToString().Trim(), _
                                          reader("Col2").ToString().Trim())
                    End While
                End Using

                conn.Close()
            End Using
        End Using

        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
    End Sub
End Module