Pages

Monday, 25 November 2013

Adding Animation In Activity

For particular view apply animation:

view_reference.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left));


Irrespective of view assign the Animation

overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

Friday, 13 September 2013

To download the images device local storage from internet



if(ImageUrl.length()>0){
File file=new File(directory,filename);
if(file.exists()&&file.length()==0){
file.delete();
}
if(!file.exists()){
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(new URL(ImageUrl).openStream());
bitmap.compress(CompressFormat.JPEG, 50, ostream);
ostream.flush();
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Download the multiple files/documents from Internet to android device storage


//here we are checking the directory already exists or not



File directory = new File("file directory name/full path");
        if(!directory.exists()){
            directory.mkdirs();
        }

//for loop to download the multiple files.
    for(int i=0; i<presentationsList.size();i++){
             
           File file=new File(directory, filename);
//here we checking the if file already exists or not. and even if the file size is zero we delete the file and recreate the file.
          if(file.exists() && file.length()==0){
              file.delete();
          }
   
//here is the actual stuff to download the file.

           if(!file.exists()){
             
               try
               {
        URLConnection ucon = new URL(proved the url here).openConnection();
                    InputStream is = ucon.getInputStream();
                     fsize=ucon.getContentLength();
               
                    
                BufferedInputStream bis = new BufferedInputStream(is);
               ByteArrayBuffer baf = new ByteArrayBuffer(ucon.getContentLength());
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                    }
                   
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baf.toByteArray());
                    fos.flush();
                    fos.close();

               //if the downloaded file size is less than the actual file size then we remove the file

                   if(file.length()<fsize){       
                         if(file.exists())
                             file.delete();
                     }                   
               }
               catch (Exception e)
               {
                   if(file.length()<fsize){       
                        if(file.exists())
                            file.delete();
                    }    
                   e.printStackTrace();
               }
             }
             }

Android custom alert dialog and To fill the device width


final Dialog  dialog=new Dialog(AgendaDetails.this);
         dialog.setTitle("Set reminder");
         dialog.setContentView(R.layout.alertdialoglist);
                        
         ListView listView = (ListView) dialog.findViewById(R.id.listView1);
         listView.setAdapter(new ReminderViewadapter(AgendaDetails.this));
                  

// here we need to set the layout parameter to the alert dialogue.

         WindowManager.LayoutParams lp = new        WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.show();
            dialog.getWindow().setAttributes(lp);

Android device Calendar Integration from Application

To add the event to device calendar using intent:

This intent will open the calnder add/edit the event screen:

                                    Intent intent = new Intent(Intent.ACTION_EDIT);
                                    intent.setType("vnd.android.cursor.item/event");
                                    intent.putExtra("beginTime", stdate);
                                    intent.putExtra("allDay", false);
                                    intent.putExtra("endTime", enddate);
                                    intent.putExtra("title", title_name);
                                    intent.putExtra("description", "");
                                    intent.putExtra("eventLocation", location);

                                    startActivity(intent);



Below provided Event add/remove and Reminder add/remove Uri's work with api level 8 and above .
if your are developing application with below api level 8 you need to change  the content Uri to
 if(Build.VERSION.SDK_INT >= 8){
      Uri.parse("content://com.android.calendar/events")
    }else {
      Uri.parse("content://calendar/events")
    }

To work with calender provider you need to mention the calendar permission in manifest.xml
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

To add the event to device calendar in background:   

This will add the event with help of calendar provider.
If you are developing the application using the api level 14 or above you can directly use the CalendarContract class and it's constants instead of below used strings.

 Uri eventUriString = Uri.parse("content://com.android.calendar/events");
            
             ContentValues eventValues = new ContentValues();

             eventValues.put("calendar_id", 1); // id, We need to choose from our mobile for primary its 1
             eventValues.put("title", title);
             eventValues.put("description", info);
             eventValues.put("eventLocation", place);
             eventValues.put("dtstart", startDate);
             eventValues.put("dtend", endDate);
             eventValues.put("eventTimezone", TimeZone.getDefault().getID());
             eventValues.put("eventStatus", 1); // This information is sufficient for     most entries tentative (0), confirmed (1) or canceled (2):
             eventValues.put("hasAlarm", 1); // 0 for false, 1 for true
        
             Uri eventUri = cr.insert(eventUriString, eventValues);


             
            //to get the last inserted event id
             long eventID = Long.parseLong(eventUri.getLastPathSegment());


To delete the event from calendar id:

If you are developing the application using the api level 14 or above you can directly use the CalendarContract class and it's constants instead of below used strings.
Uri eventUri = Uri.parse("content://com.android.calendar/events");  // or 
         Uri deleteUri = null;
         deleteUri = ContentUris.withAppendedId(eventUri, id);
         int rows = cr.delete(deleteUri, null, null);


To add the reminder for particular Event:

If you are developing the application using the api level 14 or above you can directly use the CalendarContract class and it's constants instead of below used strings. 

ContentValues reminders = new ContentValues();
      reminders.put("event_id", event_id);
      reminders.put("method", 1);//Reminder.METHOD_ALERT constant value is 1
      reminders.put("minutes", mReminders.get(pos));//Passing this as -1 will use the default reminder minutes.
        Uri uri2 = Uri.parse("content://com.android.calendar/reminders");
            getContentResolver().insert(uri2, reminders);   

To get the particular Event reminders:

If you are developing the application using the api level 14 or above you can directly use the CalendarContract class and it's constants instead of below used strings. 

 Uri uri = Uri.parse("content://com.android.calendar/reminders");
    Cursor cursor;
     
     cursor=getContentResolver().query(uri, null,"event_id = ?", new String[]{cal_Id}, null);
       
           if (cursor!=null && cursor.moveToFirst()) {
                do {
                    reminder_BO=new Reminder_BO();
                    reminder_BO.set_id(cursor.getString(cursor.getColumnIndex("_id")));
                    reminder_BO.setEvent_id(cursor.getString(cursor.getColumnIndex("event_id")));
                    reminder_BO.setMinutes(cursor.getString(cursor.getColumnIndex("minutes")));
                    reminder_BO.setMethod(cursor.getString(cursor.getColumnIndex("method")));
         reminders.add(reminder_BO);
                } while (cursor.moveToNext());
            }
          
        cursor.close();

To remove the particular event reminder :


If you are developing the application using the api level 14 or above you can directly use the CalendarContract class and it's constants instead of below used strings. 

    Uri uri = Uri.parse("content://com.android.calendar/reminders");
                                   int rows= getContentResolver().delete(uri, "event_id = ? and _id = ?", new String[]{mEventReminders.get(position).get(pos).getEvent_id(),mEventReminders.get(position).get(pos).get_id()});






Thursday, 28 February 2013

android sqlite helper class


public class DatabaseHandler extends SQLiteOpenHelper {

// Database Name
    private static final String DATABASE_NAME = "notesManager";

    // PersonNotes table name
    private static final String TABLE_NOTES = "PersonNotes";

    //  Columns names for PersonNotes table
    private static final String KEY_ID = "id";
    private static final String KEY_NOTE = "note";
    private static final String KEY_CREATED_AT = "createdAt";
    private static final String KEY_TO_PERSONID = "toPersonID";
    private static final String KEY_CUR_PERSONID = "cPersonID";

 // PersonSessions table name
    private static final String TABLE_SESSIONS = "PersonSession";

    //  Columns names for PersonSessions table
  //  private static final String KEY_ID = "id";
    private static final String KEY_SESSIONID = "eventId";
    private static final String KEY_TITLE = "title";
    private static final String KEY_SUMMARY = "summary";
    private static final String KEY_TIME = "time";
    private static final String KEY_LOCATION = "location";
  private static final String KEY_DATE = "date";
    private static final String KEY_TIMEINSEC = "timeinsec";
    private static final int version=1;
    public DatabaseHandler(Context context,CursorFactory factory){
    super(context, DATABASE_NAME, factory, version);
    }
 
    public DatabaseHandler(Context context, String name, CursorFactory factory,
int version) {
super(context, DATABASE_NAME, factory, version);

}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NOTES + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL," + KEY_NOTE + " TEXT," + KEY_CUR_PERSONID + " TEXT,"+ KEY_TO_PERSONID + " TEXT,"  + KEY_CREATED_AT + " TEXT" + ")";

String CREATE_SESSIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_SESSIONS + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL," + KEY_SESSIONID + " TEXT," + KEY_CUR_PERSONID + " TEXT,"+ KEY_TITLE + " TEXT,"+ KEY_SUMMARY + " TEXT,"+ KEY_TIME + " TEXT," + KEY_LOCATION + " TEXT," + KEY_DATE + " TEXT ," + KEY_TIMEINSEC + " REAL " +")";

       db.execSQL(CREATE_NOTES_TABLE);
       db.execSQL(CREATE_SESSIONS_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SESSIONS);
        // Create tables again
        onCreate(db);
}


 
    /** to get the particular person notes*/
    public List<Note> getPersonNotes(String cur_PersonId,String to_PersonId) {
        List<Note> notesList = new ArrayList<Note>();
     
        SQLiteDatabase db = this.getWritableDatabase();
     
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NOTES +
                " where " + KEY_CUR_PERSONID + " = ? AND  " + KEY_TO_PERSONID +  " = ? " , new String[] { cur_PersonId, to_PersonId});


     
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
            Note note = new Note();
                note.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
                note.setNote(cursor.getString(cursor.getColumnIndex(KEY_NOTE)));
                note.setCur_personId(cursor.getString(cursor.getColumnIndex(KEY_CUR_PERSONID)));
                note.setTo_personId(cursor.getString(cursor.getColumnIndex(KEY_TO_PERSONID)));
                note.setCreatedAt(cursor.getString(cursor.getColumnIndex(KEY_CREATED_AT)));
                // Adding contact to list
                notesList.add(note);
            } while (cursor.moveToNext());
        }

        if(cursor != null)
        cursor.close();
        if(db != null)
        db.close();
        return notesList;
    }


    // Deleting single note
    public void deleteNote(Note note) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NOTES, KEY_ID + " = ?",  new String[] { String.valueOf(note.getId()) });

        if(db != null)
        db.close();
    }

    // Getting notes Count
    public int getNotesCount() {
        String countQuery = "SELECT  * FROM " + TABLE_NOTES;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        if(cursor != null)
        cursor.close();
        if(db != null)
        db.close();
        return cursor.getCount();
    }

    // Adding new session
    public long addSession(Session session) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_SESSIONID, session.getEventId());
        values.put(KEY_CUR_PERSONID, session.getCurPersonId());
        values.put(KEY_TITLE, session.getTitle());
        values.put(KEY_SUMMARY, session.getSummary());
        values.put(KEY_TIME, session.getTime());
        values.put(KEY_LOCATION, session.getLocation());
        values.put(KEY_DATE, session.getDate());
       values.put(KEY_TIMEINSEC, session.getTimeinSec());
// System.out.println("TimeIN SEC:"+session.getTimeinSec());
        // Inserting Row
       long row= db.insert(TABLE_SESSIONS, null, values);
        db.close(); // Closing database connection
        return row;
    }
    /** to get the particular person sessions  with multiple where conditions and order by */
    public List<Session> getPersonSeesions(String cur_PersonId,String date) {
        List<Session> sessionsList = new ArrayList<Session>();
     
        SQLiteDatabase db = this.getWritableDatabase();
     
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_SESSIONS +
                " where " + KEY_CUR_PERSONID + " = ? AND  " + KEY_DATE +  " = ? ORDER BY "+ KEY_TIMEINSEC , new String[] { cur_PersonId, date});


     
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
            Session session=new Session();
            session.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
            session.setEventId(cursor.getString(cursor.getColumnIndex(KEY_SESSIONID)));
            session.setCurPersonId(cursor.getString(cursor.getColumnIndex(KEY_CUR_PERSONID)));
            session.setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE)));
            session.setSummary(cursor.getString(cursor.getColumnIndex(KEY_SUMMARY)));
            session.setTime(cursor.getString(cursor.getColumnIndex(KEY_TIME)));
            session.setLocation(cursor.getString(cursor.getColumnIndex(KEY_LOCATION)));
            session.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
         
                // Adding Session to list
                sessionsList.add(session);
            } while (cursor.moveToNext());
        }

        if(cursor != null)
        cursor.close();
        if(db != null)
        db.close();
        return sessionsList;
    }

   public int deletePersonSession(String cPid,String eventId){
   
    SQLiteDatabase db = this.getWritableDatabase();
     
     int row = db.delete(TABLE_SESSIONS,  KEY_CUR_PERSONID + " = ? AND  " + KEY_SESSIONID +  " = ?", new String[] { cPid, eventId});

    if(db!=null)
    db.close();
    return row;
    }
}

Thursday, 3 January 2013

Adding and removing events to/from calendar with content provider From android Application


private long pushAppointmentsToCalender(ContentResolver cr, String title, String addInfo, String place, long startDate, long endDate) {

Uri eventUriString = Uri.parse("content://com.android.calendar/events");

ContentValues eventValues = new ContentValues();

eventValues.put("calendar_id", 1); // id, We need to choose from our mobile for primary its 1
eventValues.put("title", title);
eventValues.put("description", addInfo);
eventValues.put("eventLocation", place);
eventValues.put("dtstart", startDate);
eventValues.put("dtend", endDate);
eventValues.put("eventTimezone", TimeZone.getDefault().toString());
eventValues.put("eventStatus", 1); // This information is sufficient for most entries tentative (0), confirmed (1) or canceled (2):
eventValues.put("hasAlarm", 0); // 0 for false, 1 for true

Uri eventUri = cr.insert(eventUriString, eventValues);
long eventID = Long.parseLong(eventUri.getLastPathSegment());
//System.out.println("event id is::"+eventID);
return eventID;

}


/** user defined method to get the next event id based on max_id+1 */
private  long getNewEventId(ContentResolver cr){    
   Uri local_uri = Uri.parse("content://com.android.calendar/events");
   Cursor cursor = cr.query(local_uri, new String [] {"MAX(_id) as max_id"}, null, null, "_id");
   cursor.moveToFirst();
   long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));  
   return max_val+1;
}


/** user defined method to delete the event based on id*/
private int deleteEventFromCalendar(ContentResolver  cr,long id){
Uri eventUri = Uri.parse("content://com.android.calendar/events");  // or
Uri deleteUri = null;
deleteUri = ContentUris.withAppendedId(eventUri, id);
int rows = cr.delete(deleteUri, null, null);
// System.out.println("Rows deleted: " + rows);
return rows;
}


Thursday, 20 December 2012

open calender to add event from android application


here are two ways to pass the start time and end time  values:::

long startTime = System.currentTimeMillis() -  24*1000 * 60 * 60;
  long endTime = System.currentTimeMillis() + 48*1000 * 60 * 60 * 2;
              (or)

Date date=(new SimpleDateFormat("MM/dd/yyyy hh:mm aa")).parse("12/23/2012 07:00 am");
                                      long startTime=date.getTime();
       Date date2=(new SimpleDateFormat("MM/dd/yyyy hh:mm aa")).parse("12/22/2012 08:30 am");
                                       long endTime=date2.getTime();



Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", "Some title");
intent.putExtra("description", "Some description");
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", endTime);
startActivity(intent);

Monday, 25 June 2012

To get the android device dimentions


public class DeviceDimentions {

Context context;
Display display;

public DeviceDimentions(Context context) {
this.context = context;
display = ((Activity) context).getWindowManager().getDefaultDisplay();
}

public int getWidth() {
return display.getWidth();
}

public int getHeight() {
return display.getHeight();
}
}

Tuesday, 12 June 2012

Dynamic radio buttons and checkbox sample code


LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(btn);

TextView view = new TextView(this);
view.setText("1. Select the correct statement in the following options :");
layout.addView(view);
int n = 5;
for (int i = 0; i < n; i++) {
  CheckBox checkedTextView=new CheckBox(this);
checkedTextView.setText(String.valueOf(i));
checkedTextView.setId(i);
checkedTextView.setOnCheckedChangeListener(this);
            layout.addView(checkedTextView);
}

LinearLayout layout2 = (LinearLayout) findViewById(R.id.ll);
layout2.addView(layout);
TextView view1 = new TextView(this);
view1.setText("2. Select one correct statement in the following options :");
layout.addView(view1);

RadioButton[] radioButtons=new RadioButton[5];
RadioGroup group=new RadioGroup(this);
group.setOrientation(RadioGroup.HORIZONTAL);
for (int i = 0; i < n; i++) {
 
radioButtons[i]=new RadioButton(this);
group.addView(radioButtons[i]);
radioButtons[i].setText(String.valueOf(i));
radioButtons[i].setId(i);
}
   layout.addView(group);
   group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

System.out.println("the checked radio button id is :"+checkedId);

}
});

}

@Override
public void onCheckedChanged(CompoundButton cb,boolean isChecked) {

Toast.makeText(getApplicationContext(),String.valueOf(cb.getId()) , Toast.LENGTH_LONG).show();
}

Thursday, 7 June 2012

Date comparision


DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");

Date d1 = df.parse("2012-01-24 12:30:00 PM");
Date d2 = df.parse("2012-01-24 02:30:00 PM");

int hoursDifference = (int)((d2.getTime() - d1.getTime()) / 3600000L);
System.out.println("Difference in hours: " + hoursDifference);

Tuesday, 29 May 2012

getting the numeric with - . from a string


//getting the only numeric values with . -
String strs = priceString.replaceAll("[^\\d-.]", "");
example: if priceString is Rs 25.73 L - 27.75 L
it returns 25.73-27.75

sqlite Database util class


public class DatabaseUtil {

private static final String TAG = "DatabaseUtil";

/**
* Database Name
*/
private static final String DATABASE_NAME = "sales_database";

/**
* Database Version
*/
private static final int DATABASE_VERSION = 1;

/**
* Table Name
*/
private static final String DATABASE_TABLE = "SalesTb";

/**
* Table columns
*/
public static final String ROWID = "_id";
public static final String SNAME = "salesman_name";
public static final String CNAME = "customer_name";
public static final String CPHONENO = "phone_numebr";
public static final String CARMODEL = "car_model";

/**
* Database creation sql statement
*/
private static final String CREATE_SALES_TABLE = "create table  "
+ DATABASE_TABLE + " (" + ROWID
+ " integer primary key autoincrement, " + SNAME
+ " text not null, " + CNAME + " text not null, " + CPHONENO
+ " text not null, " + CARMODEL + " text not null);";

/**
* Context
*/
private final Context mCtx;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

/**
* Inner private class. Database Helper class for creating and updating
* database.
*/

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

/**
* onCreate method is called for the 1st time when database doesn't
* exists.
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_SALES_TABLE);
db.execSQL(CREATE_SALES_TABLE);
}

/**
* onUpgrade method is called when database version changes.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);

db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}

/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx
*            the Context within which to work
*/
public DatabaseUtil(Context ctx) {
this.mCtx = ctx;
}

/**
* This method is used for creating/opening connection
*
* @return instance of DatabaseUtil
* @throws SQLException
*/
public DatabaseUtil open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

/**
* This method is used for closing the connection.
*/
public void close() {
mDbHelper.close();
}

/**
* This method is used to create/insert new sales record .
*/
public long createsales(ContentValues initialValues) {
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

/**
* This method will delete sales record.
*
* @param rowId
* @return boolean
*/
public boolean deletesales(long rowId) {
return mDb.delete(DATABASE_TABLE, ROWID + "=" + rowId, null) > 0;
}

/**
* This method will return Cursor holding all the Sales records.
*
* @return Cursor
*/
public Cursor fetchAllsales() {
return mDb.query(DATABASE_TABLE, new String[] { ROWID, SNAME, CNAME,
CPHONENO, CARMODEL }, null, null, null, null, null);
}

/**
* This method will return Cursor holding the specific Sales person record.
* @return Cursor
*/
public Cursor fetchsales(String name) throws SQLException {
Cursor mCursor = mDb.query(DATABASE_TABLE, new String[] { ROWID,
SNAME, CNAME, CPHONENO, CARMODEL },SNAME +"=? ", new String[]{name},
null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

}

Monday, 28 May 2012

ListView using CursorAdapter


listView = (ListView) findViewById(R.id.reviewList);
DatabaseUtil util = new DatabaseUtil(getApplicationContext());
util.open();
Cursor cursor = util.fetchAllsales();
String columns[] = { DatabaseUtil.SNAME, DatabaseUtil.CNAME,
DatabaseUtil.CPHONENO, DatabaseUtil.CARMODEL };
int to[] = { R.id.salemannameView, R.id.cusomernameview,
R.id.phonenumberview, R.id.carmodelnameview };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.reviewrow, cursor, columns, to);
listView.setAdapter(adapter);
util.close();

Wednesday, 23 May 2012

Sample Sax Handler

public class CarDetailsHandler extends DefaultHandler {

private Company company = null;
private Category category = null;
private Model model = null;
private ModelInfo modelInfo = null;
private EngineInfo engineInfo = null;
private BreakInfo breakInfo = null;
private StringBuffer buffer = null;
private List<Model> models = null;
private List<Category> categories = null;
private StandardFeatures standardFeatures;
private static CarDetailsHandler carDetailsHandler = null;

private CarDetailsHandler() {

}

public static CarDetailsHandler getInstance() {
if (carDetailsHandler == null) {
carDetailsHandler = new CarDetailsHandler();
}

return carDetailsHandler;
}

public Company getDetails() {

return company;
}

@Override
public void startDocument() throws SAXException {
company = new Company();
categories = new ArrayList<Category>();
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buffer = new StringBuffer();
System.out.println("now it's in start menthd");
if (localName.equalsIgnoreCase("category")) {
category = new Category();
models = new ArrayList<Model>();

} else if (localName.equalsIgnoreCase("model")) {
model = new Model();

} else if (localName.equalsIgnoreCase("info")) {
modelInfo = new ModelInfo();

} else if (localName.equalsIgnoreCase("engine")) {
engineInfo = new EngineInfo();

} else if (localName.equalsIgnoreCase("break")) {
breakInfo = new BreakInfo();

} else if (localName.equalsIgnoreCase("standardfeatures")) {
 standardFeatures = new StandardFeatures();

}

// Get the number of attribute
int length = attributes.getLength();

// Process each attribute
for (int i = 0; i < length; i++) {
// Get names and values for each attribute
String name = attributes.getQName(i);
String value = attributes.getValue(i);

if (localName.equalsIgnoreCase("company")
&& name.equalsIgnoreCase("name")) {
company.setName(value);

} else if (localName.equalsIgnoreCase("category")
&& name.equalsIgnoreCase("name")) {
category.setName(value);

} else if (localName.equalsIgnoreCase("model")
&& name.equalsIgnoreCase("name")) {
model.setName(value);

} else if (localName.equalsIgnoreCase("engine")) {
if (name.equalsIgnoreCase("type")) {
engineInfo.setEngineType(value);

} else if (name.equalsIgnoreCase("cc")) {
engineInfo.setEngineCC(value);

} else if (name.equalsIgnoreCase("fuelefficiency")) {
engineInfo.setFuelEfficiency(value);

}
} else if (localName.equalsIgnoreCase("break")) {
if (name.equalsIgnoreCase("front")) {
breakInfo.setFront(value);

} else if (name.equalsIgnoreCase("rear")) {
breakInfo.setRear(value);

}
}

}
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (buffer != null) {
buffer.append(ch, start, length);

}
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("company")) {
company.setCategories(categories);
} else if (localName.equalsIgnoreCase("category")) {
category.setModels(models);
models = null;
categories.add(category);
category = null;

} else if (localName.equalsIgnoreCase("model")) {
System.out.println("model going to end");
models.add(model);
model = null;

} else if (localName.equalsIgnoreCase("description")) {
category.setDescription(buffer.toString());
} else if (localName.equalsIgnoreCase("image")) {
model.setImage(buffer.toString());

} else if (localName.equalsIgnoreCase("price")) {
model.setPrice(buffer.toString());

} else if (localName.equalsIgnoreCase("info")) {
model.setModelInfo(modelInfo);
modelInfo = null;

} else if (localName.equalsIgnoreCase("engine")) {
modelInfo.setEngineInfo(engineInfo);
engineInfo = null;

} else if (localName.equalsIgnoreCase("transmission")) {
modelInfo.setTransmission(buffer.toString());

} else if (localName.equalsIgnoreCase("steering")) {
modelInfo.setSteering(buffer.toString());

} else if (localName.equalsIgnoreCase("doors")) {
modelInfo.setDoors(buffer.toString());

} else if (localName.equalsIgnoreCase("break")) {
modelInfo.setBreakesInfo(breakInfo);

} else if (localName.equalsIgnoreCase("highlights")) {
model.setHighlights(buffer.toString());
} else if (localName.equalsIgnoreCase("standardfeatures")) {
model.setStandardFeatures(standardFeatures);
standardFeatures = null;


} else if (localName.equalsIgnoreCase("exterior")) {
standardFeatures.setExterior(buffer.toString());
} else if (localName.equalsIgnoreCase("interior")) {
standardFeatures.setInterior(buffer.toString());
} else if (localName.equalsIgnoreCase("comfort")) {
standardFeatures.setComfort(buffer.toString());
} else if (localName.equalsIgnoreCase("safety")) {
standardFeatures.setSafety(buffer.toString());
}

}
}