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;
}