Thursday, 12 December 2013

Insert data in android using Sqlite

RegistrationActivity.java

package com.Registration;

import com.AppDemo.R;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
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 RegistrationActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    DBAdapter db;
    // Declare variables
    EditText fname;
    EditText lname;
    EditText dob;
    EditText address;
    EditText mobile;
    EditText email;


   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);

        // Get the resource
        fname = (EditText) findViewById(R.id.edt_Fname);
        lname = (EditText) findViewById(R.id.edt_Lnamme);
        dob = (EditText) findViewById(R.id.edt_Dob);
        address = (EditText) findViewById(R.id.edt_Address);
        mobile = (EditText) findViewById(R.id.edt_Mobile);
        email = (EditText) findViewById(R.id.edt_Email);

        Button submit = (Button) findViewById(R.id.btn_add);
        Button contact = (Button) findViewById(R.id.btn_addcontact);
        submit.setOnClickListener(this);
        contact.setOnClickListener(this);
       
        db = new DBAdapter(this);

        getData();
    }

    private void addData(String fname, String lname, String dob,
            String address, String mobile, String email) {
        // TODO Auto-generated method stub
        db.open();
        if (db.insertContact(fname, lname, dob, address, mobile, email) >= 0) {
            Toast.makeText(this, "Add successful.", Toast.LENGTH_LONG).show();
        }
        db.close();
    }

    private void getData() {
        // TODO Auto-generated method stub
        db.open();
        Cursor c = db.getAllContacts();
        if (c.moveToFirst()) {
            do {
                DisplayContact(c);
            } while (c.moveToNext());
        }
    }

    public void DisplayContact(Cursor c) {
        Toast.makeText(
                this,
                "Id: " + c.getString(0) + "\n" + "FName: " + c.getString(1)
                        + "\n" + "LName: " + c.getString(2) + "\n" + "DOB: "
                        + c.getString(3) + "\n" + "Address: " + c.getString(4)
                        + "\n" + "Mobile :" + c.getString(5) + "\n" + "Email: "
                        + c.getString(6), Toast.LENGTH_LONG).show();
    }

   
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_add:
           
            String name = fname.getText().toString();
            String surname = lname.getText().toString();
            String dobirth = dob.getText().toString();
           
            String addres = address.getText().toString();
            String mobileno = mobile.getText().toString();
            String email_id = email.getText().toString();
           
            Toast.makeText(
                    RegistrationActivity.this,
                    "Name: " + name + "\n" + "Lname: " + surname + "\n" + "DOB: "
                            + dobirth + "\n" + "Address: " + addres + "\n"
                            + "Mob: " + mobileno + "\n" + "Email: " + email_id
                            + "\n", Toast.LENGTH_LONG).show();
            addData(name, surname, dobirth, addres, mobileno, email_id);

            name = "";
            surname = "";
            dobirth = "";
            addres = "";
            mobileno = "";
            email_id = "";
           
            break;

        case R.id.btn_addcontact:
            startActivity(new Intent(RegistrationActivity.this, Calculation.class));
            break;
        default:
            break;
        }
    }
}

DBAdapter.java

package com.Registration;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "id";
    static final String KEY_FNAME = "fname";
    static final String KEY_LNAME = "lname";
    static final String KEY_DATE_OF_BIRTH = "dob";
    static final String KEY_CREATED_ON_DATE = "created_on";
    static final String KEY_ADDRESS = "address";
    static final String KEY_MOBILE = "mobile";
    static final String KEY_EMAIL = "email";
   
   
    static final String KEY_CAL_ID = "cal_id";
    static final String KEY_CAL_TITAL = "cal_tital";
    static final String KEY_CAL_DESCRIPTION = "ccal_description";
    static final String KEY_CAL_CREATED_DATE = "cal_created_date";
    static final String KEY_CAL_EXP_DATE = "cal_expiry_date";
   
   
    static final String TAG = "DBAdapter";
    static final String DATABASE_NAME = "Personal";
    static final String DATABASE_REGISTRATION_TABLE = "Registration";
    static final String DATABASE_CALCULATION_TABLE = "Calculation";
    static final int DATABASE_VERSION = 1;
   
    /*public void onCreate(SQLiteDatabase db) {
        String CREATE_REGISTRATION_TABLE = "CREATE TABLE " + DATABASE_REGISTRATION_TABLE + "("
                + KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT," + KEY_LNAME + "TEXT,"+ KEY_ADDRESS + "TEXT,"
                + KEY_MOBILE + " TEXT," +  KEY_EMAIL + " TEXT" +")";
        db.execSQL(DATABASE_REGISTRATION_TABLE);
    }*/
   
    static final String DATABASE_CREATE = "create table Registration (id integer primary key autoincrement, "
            + "fname text not null, lname text not null, dob text null, created_on text null, address text not null, mobile text not null, email text not null);";
   
    final Context context;
    DatabaseHelper DBHelper;
    SQLiteDatabase db;
    Calendar currentDate;
    SimpleDateFormat formatter;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
        formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS Registration");
            onCreate(db);
        }
    }

    // ---opens the database---
    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a contact into the database---
    public long insertContact(String fname, String lname, String dob, String address, String mobile, String email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_FNAME, fname);
        initialValues.put(KEY_LNAME, lname);
        initialValues.put(KEY_DATE_OF_BIRTH, dob);
        //initialValues.put(KEY_CREATED_ON_DATE, formatter.format(currentDate.getTime()));
        initialValues.put(KEY_ADDRESS, address);
        initialValues.put(KEY_MOBILE, mobile);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(DATABASE_REGISTRATION_TABLE, null, initialValues);
    }

    // ---deletes a particular contact---
    public boolean deleteContact(long rowId) {
        return db.delete(DATABASE_REGISTRATION_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    // ---retrieves all the contacts---
    public Cursor getAllContacts() {
        return db.query(DATABASE_REGISTRATION_TABLE, new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_DATE_OF_BIRTH, KEY_ADDRESS, KEY_MOBILE,
                KEY_EMAIL }, null, null, null, null, null);
    }

    // ---retrieves a particular contact---
    public Cursor getContact(long rowId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_REGISTRATION_TABLE, new String[] {
                KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_DATE_OF_BIRTH, KEY_ADDRESS, KEY_MOBILE, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
                null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    // ---updates a contact---
    public boolean updateContact(long rowId, String fname, String lname, String dob, String address, String mobile, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_FNAME, fname);
        args.put(KEY_LNAME, lname);
        args.put(KEY_DATE_OF_BIRTH, dob);
        args.put(KEY_ADDRESS, address);
        args.put(KEY_MOBILE, mobile);
        args.put(KEY_EMAIL, email);
       
        return db.update(DATABASE_REGISTRATION_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}


Thursday, 7 February 2013

Dynamically create button in android


MainActivity.java


public class MainActivity extends Activity { 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/** Call customButton Method */
customButton();
}

private void customButton() {
// TODO Auto-generated method stub
Button myButton = new Button(this);
myButton.setText("Click Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.btn_layout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Hello Friends", Toast.LENGTH_LONG).show();
}
});
}
}


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:background="@drawable/dynamic"
    android:orientation="vertical"
    tools:context=".MainActivity" >

 <LinearLayout
        android:id="@+id/btn_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </LinearLayout>

</LinearLayout>

Friday, 4 January 2013

Image zoomin and zoomout in android


Normal Image Screen


Zoomout Image Screen

Zoomin Image Screen

MainActivity.java

package com.example.image_zoomin_zoomout;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.FloatMath;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MainActivity extends Activity  implements  OnTouchListener{

/**Variables Declaration*/
private static final String TAG = "Touch";
    @SuppressWarnings("unused")
    private static final float MIN_ZOOM = 1f,MAX_ZOOM = 1f;

    // These matrices will be used to scale points of the image
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();

    // The 3 states (events) which the user is trying to perform
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // these PointF objects are used to record the point(s) the user is touching
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ImageView imv = (ImageView)findViewById(R.id.imageView1);
        imv.setOnTouchListener(this);
    }
    
    public boolean onTouch(View v, MotionEvent event)
    {
    ImageView imv = (ImageView) v ;
    imv.setScaleType(ImageView.ScaleType.MATRIX);
    float scale;
   
    dumpEvent(event);
   
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG,"Mode =Drage");
mode = DRAG;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode =NONE;
Log.d(TAG, "Mode = None");
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if(oldDist > 10f)
{
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) 
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
}
else if (mode == ZOOM) 
{
float newDist = spacing (event);
Log.d(TAG, "newDistance=" +newDist);
if (newDist > 5f) 
{
matrix.set(savedMatrix);
scale = newDist / oldDist;
// setting the scaling of the matrix...if scale > 1 means zoom in...if scale < 1 means zoom out
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;

}
    imv.setImageMatrix(matrix);
   
return true;
   
    }

/*
     * --------------------------------------------------------------------------
     * Method: spacing Parameters: MotionEvent Returns: float Description:
     * checks the spacing between the two fingers on touch
     * ----------------------------------------------------
     */
    
    private float spacing(MotionEvent event) {
// TODO Auto-generated method stub
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
   
    return FloatMath.sqrt(x * x + y *y);
}
    
    /*
     * --------------------------------------------------------------------------
     * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
     * Description: calculates the midpoint between the two fingers
     * ------------------------------------------------------------
     */
    
    private void midPoint(PointF point, MotionEvent event) {
// TODO Auto-generated method stub
   
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
   
    point.set(x/2, y/2);    
    }
    
    /** Show an event in the LogCat view, for debugging */
private void dumpEvent(MotionEvent event) {
// TODO Auto-generated method stub
String names[] = {"DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new  StringBuilder();
int action = event.getAction();
int actionCode =  action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) 
{
sb.append("(paid").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) 
{
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
       sb.append(")=").append((int) event.getX(i));
       sb.append(",").append((int) event.getY(i));
           if (i + 1 < event.getPointerCount())
               sb.append(";");
}
sb.append("]");
        Log.d("Touch Events ---------", sb.toString());
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}


Layout : 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="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="422dp"
        android:src="@drawable/android" />

</LinearLayout>
Download : Source