public static IEnumerable <TextMessage> GetConvoFromCursor(ContentResolver cr, ICursor c)
        {
            int depth        = c.Count;
            var listMessages = new List <TextMessage>();

            if (c.MoveToFirst())
            {
                do
                {
                    string messageType = c.GetString(c.GetColumnIndex("ct_t"));

                    if (messageType != null && messageType.Contains("application/vnd.wap.multipart"))
                    {
                        string messageId = c.GetString(c.GetColumnIndex("_id"));
                        listMessages.Add(MultimediaHelper.GetMessageById(cr, c, messageId));
                    }
                    else
                    {
                        string strDate = c.GetString(c.GetColumnIndex("date"));

                        listMessages.Add(new TextMessage(
                                             c.GetString(c.GetColumnIndex("thread_id")),
                                             c.GetString(c.GetColumnIndex("_id")),
                                             c.GetString(c.GetColumnIndex("body")),     //message
                                             DateTimeHelper.GetDateFromString(strDate), //date
                                             c.GetString(c.GetColumnIndex("type"))));   //whether the message is inbound or outbound
                    }
                }while (c.MoveToNext());
            }

            var orderedList = listMessages.OrderBy(x => x.Timestamp);

            return(orderedList);
        }
Exemplo n.º 2
0
        public static DownloadInfo DownloadInfo(string uri)
        {
            Android.App.DownloadManager.Query query = new Android.App.DownloadManager.Query();

            //query.SetFilterByStatus(DownloadStatus.Pending | DownloadStatus.Running | DownloadStatus.Paused);

            Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");

            ICursor cursor = downloadManager.InvokeQuery(query);

            while (cursor.MoveToNext())
            {
                string url = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnUri));

                if (url == uri)
                {
                    DownloadInfo info = new DownloadInfo();
                    info.Uri            = url;
                    info.LocalUri       = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnLocalUri));
                    info.Id             = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnId));
                    info.title          = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnTitle));
                    info.Status         = (DownloadStatus)cursor.GetInt(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnStatus));
                    info.ByteDownloaded = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnBytesDownloadedSoFar));
                    info.ByteTotal      = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnTotalSizeBytes));

                    cursor.Close();
                    return(info);
                }
            }

            cursor.Close();

            return(null);
        }
Exemplo n.º 3
0
        public static DownloadInfo DownloadInfo(long downId)
        {
            Android.App.DownloadManager.Query query = new Android.App.DownloadManager.Query();

            query.SetFilterById(downId);

            Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");

            ICursor cursor = downloadManager.InvokeQuery(query);

            if (cursor.Count > 0 && cursor.MoveToFirst())
            {
                string uri = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnUri));

                DownloadInfo info = new DownloadInfo();
                info.Uri            = uri;
                info.LocalUri       = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnLocalUri));
                info.Id             = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnId));
                info.title          = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnTitle));
                info.Status         = (DownloadStatus)cursor.GetInt(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnStatus));
                info.ByteDownloaded = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnBytesDownloadedSoFar));
                info.ByteTotal      = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnTotalSizeBytes));

                cursor.Close();
                return(info);
            }

            cursor.Close();

            return(null);
        }
Exemplo n.º 4
0
        internal static IEnumerable <Genre> ToGenres(this ICursor cursor)
        {
            var idColumn   = cursor.GetColumnIndex(MediaStore.Audio.Genres.InterfaceConsts.Id);
            var nameColumn = cursor.GetColumnIndex(MediaStore.Audio.Genres.InterfaceConsts.Name);

            var genres = new List <Genre>();

            if (cursor.MoveToFirst())
            {
                do
                {
                    var genre = cursor.ToGenre(idColumn, nameColumn);
                    genres.Add(genre);
                } while (cursor.MoveToNext());
            }

            return(genres);
        }
        internal static IEnumerable <Album> ToAlbums(this ICursor cursor)
        {
            var idColumn            = cursor.GetColumnIndex(MediaStore.Audio.Albums.InterfaceConsts.Id);
            var albumColumn         = cursor.GetColumnIndex(MediaStore.Audio.Albums.InterfaceConsts.Album);
            var artistColumn        = cursor.GetColumnIndex(MediaStore.Audio.Albums.InterfaceConsts.Artist);
            var numberOfSongsColumn = cursor.GetColumnIndex(MediaStore.Audio.Albums.InterfaceConsts.NumberOfSongs);

            if (cursor.MoveToFirst())
            {
                do
                {
                    yield return(cursor.ToAlbum(idColumn, albumColumn, artistColumn, numberOfSongsColumn));
                } while (cursor.MoveToLast());
            }

            cursor?.Close();
            cursor?.Dispose();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.registration);

            myDB              = new DBHelperClass(this);
            alert             = new Android.App.AlertDialog.Builder(this);
            reg_username      = FindViewById <EditText>(Resource.Id.reguserID);
            reg_email         = FindViewById <EditText>(Resource.Id.reguserEmail);
            reg_contact       = FindViewById <EditText>(Resource.Id.regContact);
            reg_passwd        = FindViewById <EditText>(Resource.Id.pswd);
            reg_confirmpasswd = FindViewById <EditText>(Resource.Id.ConfirmPswd);
            RegSignUpBtn      = FindViewById <Button>(Resource.Id.signupBtn);

            //auto generate id

            myid = FindViewById <TextView>(Resource.Id.user_id);
            cr   = myDB.SelectMyId();
            cr.MoveToFirst();
            myid.Text = (cr.GetInt(cr.GetColumnIndex("id")) + 1).ToString();
            reg_confirmpasswd.TextChanged += check_password;
            reg_email.TextChanged         += login;
            //email validation

            RegSignUpBtn.Click += delegate
            {
                var ruserName        = reg_username.Text;
                var rEmail           = reg_email.Text;
                var rContact         = reg_contact.Text;
                var rPassword        = reg_passwd.Text;
                var rConfirmPassword = reg_passwd.Text;

                if (ruserName.Trim().Equals("") || ruserName.Length < 0 || rEmail.Trim().Equals("") ||
                    rEmail.Length < 0 || rContact.Trim().Equals("") ||
                    rContact.Length < 0 || rPassword.Trim().Equals("") || rPassword.Length < 0 ||
                    rConfirmPassword.Trim().Equals("") || rConfirmPassword.Length < 0)
                {
                    alert.SetTitle("Error");
                    alert.SetMessage("Field can not be empty");
                    alert.SetPositiveButton("OK", alertOKButton);
                    alert.SetNegativeButton("Cancel", alertOKButton);
                    Dialog myDialog = alert.Create();
                    myDialog.Show();
                }

                else
                {
                    myDB.InsertValue(myid.Text, ruserName, rEmail, rContact, rPassword);

                    myDB.SelectMydata();

                    Intent newScreen = new Intent(this, typeof(MainActivity));
                    newScreen.PutExtra("userName", reg_username.Text);
                    StartActivity(newScreen);
                }
            };
        }
Exemplo n.º 7
0
        internal static IEnumerable <Artist> ToArtists(this ICursor cursor)
        {
            var idColumn             = cursor.GetColumnIndex(MediaStore.Audio.Artists.InterfaceConsts.Id);
            var artistColum          = cursor.GetColumnIndex(MediaStore.Audio.Artists.InterfaceConsts.Artist);
            var numberOfTracksColumn = cursor.GetColumnIndex(MediaStore.Audio.Artists.InterfaceConsts.NumberOfTracks);
            var numberofAlbumsColumn = cursor.GetColumnIndex(MediaStore.Audio.Artists.InterfaceConsts.NumberOfAlbums);

            if (cursor.MoveToFirst())
            {
                do
                {
                    yield return(cursor.ToArtist(idColumn, artistColum, numberOfTracksColumn, numberofAlbumsColumn));
                } while (cursor.MoveToNext());
            }

            cursor?.Close();
            cursor?.Dispose();
        }
        public string getCartItemQty(String id)
        {
            db = ReadableDatabase;
            string  qry    = "Select *  from " + CART_TABLE + " where " + VARIENT_ID + " = " + id;
            ICursor cursor = db.RawQuery(qry, null);

            cursor.MoveToFirst();
            return(cursor.GetString(cursor.GetColumnIndex(COLUMN_QTY)));
        }
Exemplo n.º 9
0
        //메시지 DB를 탐색하여, 각 대화중 가장 최신 MMS를 찾아 메모리에 올림.
        public void UpdateLastMMS()
        {
            ContentResolver cr  = Application.Context.ContentResolver;
            Uri             uri = Uri.Parse("content://mms/");

            string[] projection = new string[] { "DISTINCT thread_id", "_id", "ct_t", "read", "date", "m_type" };
            string   selection  = "thread_id IS NOT NULL) GROUP BY (thread_id";
            string   sortOrder  = "date desc";
            ICursor  cursor     = cr.Query(uri, projection, selection, null, sortOrder);

            if (cursor != null)
            {
                if (cursor.Count > 0)
                {
                    while (cursor.MoveToNext())
                    {
                        string id        = cursor.GetString(cursor.GetColumnIndex("_id"));
                        string mmsType   = cursor.GetString(cursor.GetColumnIndex("ct_t"));
                        int    readState = cursor.GetInt(cursor.GetColumnIndex("read"));
                        long   time      = cursor.GetLong(cursor.GetColumnIndex("date"));
                        long   thread_id = cursor.GetLong(cursor.GetColumnIndexOrThrow("thread_id"));
                        int    type      = cursor.GetInt(cursor.GetColumnIndexOrThrow("m_type"));
                        if ("application/vnd.wap.multipart.related".Equals(mmsType) || "application/vnd.wap.multipart.mixed".Equals(mmsType))
                        {
                            //this is MMS
                            MultiMediaMessage objMMS = ReadMMS(id);
                            objMMS.Id        = id;
                            objMMS.ReadState = readState;
                            objMMS.Time      = time * 1000;     //1000을 곱하지 않으면 1970년으로 표기됨
                            objMMS.Thread_id = thread_id;
                            objMMS.Type      = type == 132 ? (int)TextMessage.MESSAGE_TYPE.RECEIVED : (int)TextMessage.MESSAGE_TYPE.SENT;

                            UpdateLastMessage(objMMS);
                        }
                        else
                        {
                            //this is SMS
                            //throw new Exception("알 수 없는 MMS 유형");
                        }
                    }
                }
                cursor.Close();
            }
        }
Exemplo n.º 10
0
        public bool LoadPrescription(int medicationID)
        {
            SQLiteDatabase sqlDatabase = null;

            try
            {
                var     sql    = @"SELECT [ID], [PrescriptionType], [WeeklyDay], [MonthlyDay] FROM [Prescription] WHERE [MedicationID] = ?";
                Globals dbHelp = new Globals();
                dbHelp.OpenDatabase();
                sqlDatabase = dbHelp.GetSQLiteDatabase();
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    ICursor prescription = sqlDatabase.RawQuery(sql, new string[] { medicationID.ToString() });
                    if (prescription.Count > 0)
                    {
                        prescription.MoveToFirst();
                        ID = prescription.GetInt(prescription.GetColumnIndex("ID"));
                        PrescriptionType = (ConstantsAndTypes.PRESCRIPTION_TYPE)prescription.GetInt(prescription.GetColumnIndex("PrescriptionType"));
                        WeeklyDay        = (ConstantsAndTypes.DAYS_OF_THE_WEEK)prescription.GetInt(prescription.GetColumnIndex("WeeklyDay"));
                        MonthlyDay       = prescription.GetInt(prescription.GetColumnIndex("MonthlyDay"));
                        IsNew            = false;
                        IsDirty          = false;
                    }
                    else
                    {
                        dbHelp.CloseDatabase();
                        return(false);
                    }
                    dbHelp.CloseDatabase();
                    return(true);
                }
                dbHelp.CloseDatabase();
                return(false);
            }
            catch (Exception e)
            {
                Log.Error(TAG, "LoadPrescription: Exception - " + e.Message);
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    sqlDatabase.Close();
                }
                return(false);
            }
        }
Exemplo n.º 11
0
        public void UpdateFileProperties(ICursor cursor)
        {
            int id           = cursor.GetInt(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnId));
            var downloadFile = Queue.Cast <DownloadFileImplementation> ().FirstOrDefault(f => f.Id == id);

            if (downloadFile != null)
            {
                UpdateFileProperties(cursor, downloadFile);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Retrieves content filename from content:// URI
        /// </summary>
        /// <param name="uri">content URI</param>
        /// <returns>filename-only part</returns>
        private string GetContentNameFromContentUri(Uri uri)
        {
            ICursor cursor = this.resolver.Query(uri, null, null, null, null);

            cursor.MoveToFirst();

            int nameIndex = cursor.GetColumnIndex(global::Android.Provider.MediaStore.MediaColumns.DisplayName);

            return(nameIndex >= 0 ? cursor.GetString(nameIndex) : null);
        }
Exemplo n.º 13
0
 //gets
 public List<ChildModel> GetChildren()
 {
     SQLiteDatabase db = helper.WritableDatabase;
     String[] columns = { DBHelper.CHILD_FIRST_NAME, DBHelper.CHILD_LAST_NAME, DBHelper.CHILD_EMAIL, DBHelper.CHILD_PHONE, DBHelper.CHILD_PARENT_NAME};
     List<ChildModel> children = new List<ChildModel>();
     ICursor cursor = db.Query(DBHelper.CHILD_TABLE_NAME, columns, null, null, null, null, null);
     while(cursor.MoveToNext())
     {
         String fName = cursor.GetString(cursor.GetColumnIndex(DBHelper.CHILD_FIRST_NAME));
         String sName = cursor.GetString(cursor.GetColumnIndex(DBHelper.CHILD_LAST_NAME));
         String sEmail = cursor.GetString(cursor.GetColumnIndex(DBHelper.CHILD_EMAIL));
         String sPhone = cursor.GetString(cursor.GetColumnIndex(DBHelper.CHILD_PHONE));
         String sParentName = cursor.GetString(cursor.GetColumnIndex(DBHelper.CHILD_PARENT_NAME));
         ChildModel c = new ChildModel(fName, sName, sEmail, sPhone, sParentName);
         children.Add(c);
     }
     
     return children;
 }
            /**
             * Grabs metadata for a document specified by URI, logs it to the screen.
             */
            public void DumpImageMetaData(Android.Net.Uri uri)
            {
                Log.Info(TAG, "Fetching Image Meta Data:");

                // The query, since it only applies to a single document, will only return one row.
                // no need to filter, sort, or select fields, since we want all fields for one
                // document.
                ICursor cursor = Activity.ContentResolver.Query(uri, null, null, null, null, null);

                try {
                    // moveToFirst() returns false if the cursor has 0 rows.  Very handy for
                    // "if there's anything to look at, look at it" conditionals.
                    if (cursor != null && cursor.MoveToFirst())
                    {
                        // Note it's called "Display Name".  This is provider-specific, and
                        // might not necessarily be the file name.
                        string displayName = cursor.GetString(
                            cursor.GetColumnIndex(OpenableColumns.DisplayName));
                        Log.Info(TAG, "Display Name: " + displayName);

                        int sizeIndex = cursor.GetColumnIndex(OpenableColumns.Size);
                        // If the size is unknown, the value stored is null.  But since an int can't be
                        // null in java, the behavior is implementation-specific, which is just a fancy
                        // term for "unpredictable".  So as a rule, check if it's null before assigning
                        // to an int.  This will happen often:  The storage API allows for remote
                        // files, whose size might not be locally known.
                        String size = null;
                        if (!cursor.IsNull(sizeIndex))
                        {
                            // Technically the column stores an int, but cursor.getString will do the
                            // conversion automatically.
                            size = cursor.GetString(sizeIndex);
                        }
                        else
                        {
                            size = "Unknown";
                        }
                        Log.Info(TAG, "Size: " + size);
                    }
                } finally {
                    cursor.Close();
                }
            }
Exemplo n.º 15
0
        private string GetAudioFilePathFromUri(Android.Net.Uri uri)
        {
            ICursor cursor = this.BaseContext.ContentResolver
                             .Query(this.uri, null, null, null, null);

            cursor.MoveToFirst();
            int index = cursor.GetColumnIndex(MediaStore.Audio.AudioColumns.Data);

            return(cursor.GetString(index));
        }
Exemplo n.º 16
0
        private void AddData()
        {
            ICursor selectData = sqlitedb.RawQuery("select * from allBuses_ where number ='" + txtNumber.Text + "'", new string[] { });

            if (selectData.Count > 0)
            {
                selectData.MoveToFirst();
                do
                {
                    bus            = new allBuses_();
                    bus.number     = selectData.GetString(selectData.GetColumnIndex("number"));
                    bus.wayTo      = selectData.GetString(selectData.GetColumnIndex("wayTo"));
                    bus.wayFrom    = selectData.GetString(selectData.GetColumnIndex("wayFrom"));
                    bus.allStopID  = selectData.GetString(selectData.GetColumnIndex("allStopID"));
                    bus.fullTiming = selectData.GetString(selectData.GetColumnIndex("fullTiming"));
                } while (selectData.MoveToNext());
                selectData.Close();
            }
        }
        List <Contact> CreateContact(ICursor cursor, Android.Content.Context ctx)
        {
            List <Contact> contacts = new List <Contact>();

            if (cursor != null)
            {
                try
                {
                    int      contactIdIndex   = cursor.GetColumnIndex(ContactsContract.CommonDataKinds.Email.InterfaceConsts.ContactId);
                    int      displayNameIndex = cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName);
                    int      emailIndex       = cursor.GetColumnIndex(ContactsContract.CommonDataKinds.Email.InterfaceConsts.Data);
                    long     contactId;
                    string   displayName;
                    string[] address;
                    while (cursor.MoveToNext())
                    {
                        contactId   = cursor.GetLong(contactIdIndex);
                        displayName = cursor.GetString(displayNameIndex);
                        address     = new[] { cursor.GetString(emailIndex) };

                        var contact = new Contact
                        {
                            Name   = displayName,
                            Emails = address,
                        };
                        if (!string.IsNullOrWhiteSpace(contact.Name) && (contact.Emails.Count() > 0))
                        {
                            contacts.Add(contact);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                finally
                {
                    cursor.Close();
                }
            }
            return(contacts);
        }
Exemplo n.º 18
0
        public System.String PhonesByCursor(ICursor cur)
        {
            System.String phones = "";
            int           id     = cur.GetInt(cur.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));

            if (System.Int16.Parse(cur.GetString(cur.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.HasPhoneNumber))) > 0)
            {
                var     loader = new CursorLoader(_context, ContactsContract.CommonDataKinds.Phone.ContentUri, null, ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + " = " + id, null, null);
                ICursor pCur;
                pCur = (ICursor)loader.LoadInBackground();

                while (pCur.MoveToNext())
                {
                    phones += pCur.GetString(pCur.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data)) + "\r\n";
                }
                pCur.Close();
            }
            return(phones);
        }
Exemplo n.º 19
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.product_activity);
            spinner_category       = FindViewById <Spinner>(Resource.Id.pro_spinner);
            pro_img                = FindViewById <Spinner>(Resource.Id.spinner_pro);
            spinner_unit           = FindViewById <Spinner>(Resource.Id.pro_unit);
            product_name           = FindViewById <EditText>(Resource.Id.product_name);
            product_purchase_price = FindViewById <EditText>(Resource.Id.product_purchase);
            product_sell_price     = FindViewById <EditText>(Resource.Id.product_sell);
            product_image          = FindViewById <ImageView>(Resource.Id.product_img_view);
            product_add            = FindViewById <Button>(Resource.Id.product_btn);
            logo            = FindViewById <ImageView>(Resource.Id.image_pro);
            text_pro_logo   = FindViewById <TextView>(Resource.Id.product_logo);
            pro_img.Adapter = new ArrayAdapter
                                  (this, Android.Resource.Layout.SimpleListItem1, cat_img_list);

            pro_img.ItemSelected          += MyProImgSelectedMethod;
            product_add.Click             += AddProduct;
            spinner_category.ItemSelected += MyItemSelectedMethod;
            spinner_unit.Adapter           = new ArrayAdapter
                                                 (this, Android.Resource.Layout.SimpleListItem1, myUnit);

            spinner_unit.ItemSelected += MyItemSelectedMethod2;
            myDB = new DBHelper(this);
            myDB.category_list();
            ic = myDB.category_list();

            int i = 0;

            while (ic.MoveToNext())
            {
                var a = ic.GetString(ic.GetColumnIndex("cat_name"));
                var b = ic.GetInt(ic.GetColumnIndex("cat_id"));
                dist.Add(a, b);
                myCategory.Add(a);
                i++;
            }
            //product_image.Click += ImageOnClick;
            spinner_category.Adapter = new ArrayAdapter
                                           (this, Android.Resource.Layout.SimpleListItem1, myCategory);
        }
        void UpdateDirectoryEntries(Uri uri)
        {
            directoryEntries.Clear();
            var contentResolver = Activity.ContentResolver;
            Uri docUri          = DocumentsContract.BuildDocumentUriUsingTree(uri, DocumentsContract.GetTreeDocumentId(uri));
            Uri childrenUri     = DocumentsContract.BuildChildDocumentsUriUsingTree(uri, DocumentsContract.GetTreeDocumentId(uri));

            try {
                using (ICursor docCursor = contentResolver.Query(docUri, DIRECTORY_SELECTION, null, null, null)) {
                    while (docCursor != null && docCursor.MoveToNext())
                    {
                        currentDirectoryTextView.Text = docCursor.GetString(
                            docCursor.GetColumnIndex(DocumentsContract.Document.ColumnDisplayName));
                    }
                }
            } catch {
            }

            try {
                using (ICursor childCursor = contentResolver.Query(childrenUri, DIRECTORY_SELECTION, null, null, null)) {
                    while (childCursor != null && childCursor.MoveToNext())
                    {
                        var entry = new DirectoryEntry();
                        entry.FileName = childCursor.GetString(childCursor.GetColumnIndex(DocumentsContract.Document.ColumnDisplayName));
                        entry.MimeType = childCursor.GetString(childCursor.GetColumnIndex(DocumentsContract.Document.ColumnMimeType));
                        directoryEntries.Add(entry);
                    }
                }

                if (directoryEntries.Count == 0)
                {
                    nothingInDirectoryTextView.Visibility = ViewStates.Visible;
                }
                else
                {
                    nothingInDirectoryTextView.Visibility = ViewStates.Gone;
                }

                adapter.DirectoryEntries = directoryEntries;
                adapter.NotifyDataSetChanged();
            } catch {
            }
        }
Exemplo n.º 21
0
        private static List <Event> QueryEvents(Context context, long beginTime, long endTime)
        {
            ContentResolver contentResolver = context.ContentResolver;

            Android.Net.Uri.Builder builder = CalendarContract.Instances.ContentUri.BuildUpon();
            ContentUris.AppendId(builder, beginTime);
            ContentUris.AppendId(builder, endTime);
            ICursor cursor = contentResolver.Query(builder.Build(), INSTANCE_PROJECTION,
                                                   null /* selection */, null /* selectionArgs */, null /* sortOrder */);

            try
            {
                int idIdx         = cursor.GetColumnIndex(CalendarContract.Instances.InterfaceConsts.Id);
                int eventIdIdx    = cursor.GetColumnIndex(CalendarContract.Instances.EventId);
                int titleIdx      = cursor.GetColumnIndex(CalendarContract.Instances.InterfaceConsts.Title);
                int beginIdx      = cursor.GetColumnIndex(CalendarContract.Instances.Begin);
                int endIdx        = cursor.GetColumnIndex(CalendarContract.Instances.End);
                int allDayIdx     = cursor.GetColumnIndex(CalendarContract.Instances.InterfaceConsts.AllDay);
                int descIdx       = cursor.GetColumnIndex(CalendarContract.Instances.InterfaceConsts.Description);
                int ownerEmailIdx = cursor.GetColumnIndex(CalendarContract.Instances.InterfaceConsts.Organizer);

                List <Event> events = new List <Event>(cursor.Count);
                while (cursor.MoveToNext())
                {
                    Event cEvent = new Event();
                    cEvent.Id          = cursor.GetLong(idIdx);
                    cEvent.EventId     = cursor.GetLong(eventIdIdx);
                    cEvent.Title       = cursor.GetString(titleIdx);
                    cEvent.Begin       = cursor.GetLong(beginIdx);
                    cEvent.End         = cursor.GetLong(endIdx);
                    cEvent.AllDay      = cursor.GetInt(allDayIdx) != 0;
                    cEvent.Description = cursor.GetString(descIdx);
                    string  ownerEmail    = cursor.GetString(ownerEmailIdx);
                    ICursor contactCursor = contentResolver.Query(ContactsContract.Data.ContentUri, CONTACT_PROJECTION,
                                                                  CONTACT_SELECTION, new String[] { ownerEmail }, null);
                    int  ownerIdIdx = contactCursor.GetColumnIndex(ContactsContract.Data.InterfaceConsts.ContactId);
                    long ownerId    = -1;
                    if (contactCursor.MoveToFirst())
                    {
                        ownerId = contactCursor.GetLong(ownerIdIdx);
                    }
                    contactCursor.Close();
                    // Use event organizer's profile picture as the notification background
                    cEvent.OwnerProfilePic = GetProfilePicture(contentResolver, context, ownerId);
                    events.Add(cEvent);
                }
                return(events);
            }
            finally {
                cursor.Close();
            }
            return(null);
        }
Exemplo n.º 22
0
        public override bool Set(Context context, ComponentName component, int badgeCount)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.LollipopMr1 && base.IsSupported(context))             //new samsung >= 5.1 use default badger system
            {
                //use default badger
                return(base.Set(context, component, badgeCount));
            }

            Uri             contentUri = Uri.Parse(CONTENT_URI);
            ContentResolver resolver   = context.ContentResolver;
            ICursor         cursor     = null;

            try
            {
                cursor = resolver.Query(contentUri, ContentProjection, "package=?", new[] { component.PackageName }, null);
                if (cursor == null)
                {
                    return(false);
                }

                string entryActivityName  = component.ClassName;
                bool   entryActivityExist = false;
                while (cursor.MoveToNext())
                {
                    int           id            = cursor.GetInt(0);
                    ContentValues contentValues = GetContentValues(component, badgeCount, false);
                    resolver.Update(contentUri, contentValues, "_id=?", new [] { id.ToString() });
                    if (entryActivityName.Equals(cursor.GetString(cursor.GetColumnIndex("class"))))
                    {
                        entryActivityExist = true;
                    }
                }

                if (!entryActivityExist)
                {
                    ContentValues contentValues = GetContentValues(component, badgeCount, true);
                    resolver.Insert(contentUri, contentValues);
                }

                return(true);
            }
            catch (Exception)
            {
                //ignored

                return(false);
            }
            finally
            {
                if (cursor != null && !cursor.IsClosed)
                {
                    cursor.Close();
                }
            }
        }
Exemplo n.º 23
0
        public override void OnChange(bool selfChange, global::Android.Net.Uri uri)
        {
            // for some reason, we get multiple calls to OnChange for the same outgoing text. ignore repeats.
            if (_mostRecentlyObservedSmsURI != null && uri.ToString() == _mostRecentlyObservedSmsURI)
            {
                return;
            }

            ICursor cursor = _context.ContentResolver.Query(uri, null, null, null, null);

            if (cursor.MoveToNext())
            {
                string protocol = cursor.GetString(cursor.GetColumnIndex("protocol"));
                int    type     = cursor.GetInt(cursor.GetColumnIndex("type"));

                int sentMessageType;

                #if __ANDROID_19__
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    sentMessageType = (int)SmsMessageType.Sent;  // API level 19
                }
                else
                #endif
                sentMessageType = 2;

                if (protocol != null || type != sentMessageType)
                {
                    return;
                }

                string         to             = cursor.GetString(cursor.GetColumnIndex("address"));
                long           unixTimeMS     = cursor.GetLong(cursor.GetColumnIndex("date"));
                DateTimeOffset dotNetDateTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()).AddMilliseconds(unixTimeMS);
                string         message        = cursor.GetString(cursor.GetColumnIndex("body"));
                cursor.Close();

                _outgoingSMS(new SmsDatum(dotNetDateTime, null, to, message));

                _mostRecentlyObservedSmsURI = uri.ToString();
            }
        }
Exemplo n.º 24
0
        private void CanYouPictureThat()
        {
            string orderBy = CreateCursor();

            Console.WriteLine("Getting column index");
            int image_column_index = _imagecursor.GetColumnIndex(orderBy);

            var count = _imagecursor.Count;

            Console.WriteLine("Found {0} photos", count);

            this.thumbnails = new Bitmap[count];
            var arrPath = new string[count];

            this.thumbnailsselection = new bool[count];

            for (int i = 0; i < count; i++)
            {
                _imagecursor.MoveToPosition(i);
                int id = _imagecursor.GetInt(image_column_index);
                int dataColumnIndex = _imagecursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);

                thumbnails[i] = MediaStore.Images.Thumbnails.GetThumbnail(ApplicationContext.ContentResolver, id, ThumbnailKind.MicroKind, null);
                arrPath[i]    = _imagecursor.GetString(dataColumnIndex);
                if (i % 25 == 0)
                {
                    Console.WriteLine("Processing {0}th photo", i);
                }
            }

            Console.WriteLine("All photos processed, creating image adapter");

            var imageAdapter = new ImageAdapter(this)
            {
                thumbIds = thumbnails
            };

            Console.WriteLine("Assigning adapter to grid view");
            _gridView.Adapter = imageAdapter;

            Console.WriteLine("done");
        }
Exemplo n.º 25
0
        public void GetNameHouse(string name1)
        {
            data.Clear();
            DBAdapter db = new DBAdapter(this);

            db.openDB();

            ICursor c = db.RetrieveList(name1);

            if (c != null)
            {
                while (c.MoveToNext())
                {
                    int    i          = c.GetInt(c.GetColumnIndex("id"));
                    string name       = c.GetString(c.GetColumnIndex("name"));
                    string nameOwner  = c.GetString(c.GetColumnIndex("namePerson"));
                    string amount     = c.GetString(c.GetColumnIndex("number"));
                    string new_amount = "Rs." + " " + amount;
                    //string dummy = name + nameOwner + amount;
                    //nameHouse.Add(dummy); //need to add something
                    //Collections.Sort(nameHouse);

                    Data d = new Data()
                    {
                        Id         = i,
                        NameHouse  = name,
                        NamePerson = nameOwner,
                        NameAmount = new_amount
                    };
                    data.Add(d);
                }
                lv         = FindViewById <ListView>(Resource.Id.listView1);
                adapter    = new CustomAdapter(this, data);
                lv.Adapter = adapter;
            }
            db.CloseDB();

            /*if (data.Count > 0)
             * {
             *      namelist.Adapter = adapter;
             * }*/
        }
Exemplo n.º 26
0
        private void LoadRawContact()
        {
            if (_ContactList != null)
            {
                _ContactList = new Dictionary <long, Contact>();
            }

            ContentResolver cr = Application.Context.ContentResolver;

            Uri uri = ContactsContract.RawContacts.ContentUri;

            string column_id           = ContactsContract.RawContacts.InterfaceConsts.Id;
            string column_contact_id   = ContactsContract.RawContacts.InterfaceConsts.ContactId;
            string column_account_name = ContactsContract.RawContacts.InterfaceConsts.AccountName;
            string column_display_name = ContactsContract.RawContacts.InterfaceConsts.DisplayNamePrimary;

            //SQLITE 조건문 설정
            string[] projection = { column_id, column_contact_id, column_account_name, column_display_name, };

            ICursor cursor = cr.Query(uri, projection, null, null, null);   //쿼리

            if (cursor != null && cursor.Count > 0)
            {
                while (cursor.MoveToNext())
                {
                    long   id           = cursor.GetLong(cursor.GetColumnIndex(projection[0]));
                    long   contact_id   = cursor.GetLong(cursor.GetColumnIndex(projection[1]));
                    string account_name = cursor.GetString(cursor.GetColumnIndex(projection[2]));
                    string display_name = cursor.GetString(cursor.GetColumnIndex(projection[3]));

                    //Contact가 신규면 생성
                    if (_ContactList.ContainsKey(contact_id) == false)
                    {
                        _ContactList.Add(contact_id, new Contact(contact_id));
                    }
                    _ContactList[contact_id].RawContacts.Add(id, new RawContact(id, contact_id, account_name, display_name));       //탐색한 RawContact삽입

                    //Android.Util.Log.Debug("Raw Contact : ", id.ToString() + "," + contact_id.ToString() + "," + account_name + "," + display_name);
                }
            }
            cursor.Close();
        }
Exemplo n.º 27
0
        public void showProductList()
        {
            ic = myDB.product_list();

            int i = 0;

            myUsersList = new List <UserObject_purchase>();
            while (ic.MoveToNext())
            {
                var a = ic.GetString(ic.GetColumnIndex("pro_name"));
                var b = ic.GetInt(ic.GetColumnIndex("purchase_price"));
                var c = ic.GetInt(ic.GetColumnIndex("pro_id"));
                Console.WriteLine(a);
                Console.WriteLine(b);
                myUsersList.Add(new UserObject_purchase(a, b, c));
                i++;
            }
            myCAdapter        = new Purchase_CustomAdapter(this, myUsersList);
            listView1.Adapter = myCAdapter;
        }
Exemplo n.º 28
0
        public bool LoadMedicationSpread()
        {
            SQLiteDatabase sqlDatabase = null;

            try
            {
                var      sql    = @"SELECT [Dosage], [FoodRelevance] FROM [MedicationSpread] WHERE [ID] = ? AND [MedicationID] = ?";
                string[] values = new string[]
                {
                    ID.ToString(),
                         MedicationID.ToString()
                };
                Globals dbHelp = new Globals();
                dbHelp.OpenDatabase();
                sqlDatabase = dbHelp.GetSQLiteDatabase();
                if (sqlDatabase != null)
                {
                    if (sqlDatabase.IsOpen)
                    {
                        ICursor medicationItem = sqlDatabase.RawQuery(sql, values);
                        if (medicationItem.Count > 0)
                        {
                            medicationItem.MoveToFirst();
                            MedicationTakeTime = new MedicationTime();
                            MedicationTakeTime.LoadMedicationTime(ID);
                            MedicationTakeReminder = new MedicationReminder();
                            MedicationTakeReminder.LoadMedicationTime(ID);
                            if (!MedicationTakeReminder.IsSet)
                            {
                                MedicationTakeReminder = null;
                            }
                            Dosage        = medicationItem.GetInt(medicationItem.GetColumnIndex("Dosage"));
                            FoodRelevance = (ConstantsAndTypes.MEDICATION_FOOD)medicationItem.GetInt(medicationItem.GetColumnIndex("FoodRelevance"));
                        }
                        else
                        {
                            dbHelp.CloseDatabase();
                            return(false);
                        }
                    }
                    dbHelp.CloseDatabase();
                }
                return(true);
            }
            catch (Exception e)
            {
                Log.Error(TAG, "LoadMedicationSpread: Exception - " + e.Message);
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    sqlDatabase.Close();
                }
                return(false);
            }
        }
Exemplo n.º 29
0
        public bool TryGetRealPathFromURI(Context context, Android.Net.Uri contentURI, out string path)
        {
            //Context context;

            if (context != null)
            {
                //context = MainApplication.CurrentContext;

                try
                {
                    ICursor imageCursor     = null;
                    string  fullPathToImage = "";

                    imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
                    imageCursor.MoveToFirst();
                    int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);

                    if (idx != -1)
                    {
                        //This works for older devices
                        fullPathToImage = imageCursor.GetString(idx);
                    }
                    else
                    {
                        //This works for newer devices
                        ICursor cursor      = null;
                        var     docID       = DocumentsContract.GetDocumentId(contentURI);
                        var     id          = docID.Split(':')[1];
                        var     whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                        var     projections = new string[] { MediaStore.Images.ImageColumns.Data };

                        // Try internal storage first
                        cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                        if (cursor.Count == 0)
                        {
                            // not found on internal storage, try external storage
                            cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                        }
                        var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                        cursor.MoveToFirst();
                        fullPathToImage = cursor.GetString(colData);
                    }
                    path = fullPathToImage;
                    return(true);
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                    Toast.MakeText(context, "Unable to get path", ToastLength.Long).Show();
                }
            }
            path = null;
            return(false);
        }
Exemplo n.º 30
0
        public Bitmap ReturnDrawableBase(long id, string path)
        {
            string[] col   = { "ColumnBitmap" };
            string[] param = { path };
            cursor = WritableDatabase.Query("ContentTable", col, "ColumnPath = ?", param, null, null, null);
            cursor.MoveToFirst();
            byte[] array = cursor.GetBlob(cursor.GetColumnIndex(COLUMN_BITMAP));
            Bitmap b     = Multitools.ConvertToBitmap(array);

            return(b);
        }
Exemplo n.º 31
0
        public void Create_Database()
        {
            HashSet<String> tableNameHashSet = new HashSet<String> ();
            tableNameHashSet.Add (WeatherContractOpen.LocationEntryOpen.TABLE_NAME);
            tableNameHashSet.Add (WeatherContractOpen.WeatherEntryOpen.TABLE_NAME);

            context.DeleteDatabase (WeatherDbOpenHelper.DATABASE_NAME);
            SQLiteDatabase db = new WeatherDbOpenHelper (
                                    this.context).WritableDatabase;
            Assert.AreEqual (true, db.IsOpen);

            // have we created the tables we want?
            c = db.RawQuery ("SELECT name FROM sqlite_master WHERE type='table'", null);

            Assert.IsTrue (c.MoveToFirst (), "Error: This means that the database has not been created correctly");

            // verify that the tables have been created
            do {
                tableNameHashSet.Remove (c.GetString (0));
            } while(c.MoveToNext ());

            // if this fails, it means that your database doesn't contain both the location entry
            // and weather entry tables
            Assert.IsTrue (tableNameHashSet.Count == 0, "Error: Your database was created without both the location entry and weather entry tables");

            // now, do our tables contain the correct columns?
            c = db.RawQuery ("PRAGMA table_info(" + WeatherContractOpen.LocationEntryOpen.TABLE_NAME + ")",
                null);

            Assert.IsTrue (c.MoveToFirst (), "Error: This means that we were unable to query the database for table information.");

            // Build a HashSet of all of the column names we want to look for
            HashSet<String> locationColumnHashSet = new HashSet<String> ();
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen._ID);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_CITY_NAME);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_COORD_LAT);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_COORD_LONG);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_LOCATION_SETTING);

            int columnNameIndex = c.GetColumnIndex ("name");
            do {
                String columnName = c.GetString (columnNameIndex);
                locationColumnHashSet.Remove (columnName);
            } while(c.MoveToNext ());

            // if this fails, it means that your database doesn't contain all of the required location
            // entry columns
            Assert.IsTrue (locationColumnHashSet.Count == 0, "Error: The database doesn't contain all of the required location entry columns");
            db.Close ();
        }
Exemplo n.º 32
0
        public override void BindView(View view, Context context, ICursor cursor)
        {
            int image_column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id);
            var imageView = (ImageView)view;
            int id = cursor.GetInt(image_column_index);

            Bitmap bm = MediaStore.Images.Thumbnails.GetThumbnail(context.ContentResolver, id, ThumbnailKind.MicroKind, null);

            BitmapDrawable drawable = imageView.Drawable as BitmapDrawable;

            if (drawable != null && drawable.Bitmap != null)
            {
                drawable.Bitmap.Recycle();
            }

            imageView.SetImageBitmap(bm);
        }
Exemplo n.º 33
0
        public override void BindView(View view, Context context, ICursor cursor)
        {
            //var textView = view.FindViewById<TextView>(Android.Resource.Id.Text1);
            //textView.Text = cursor.GetString(1); // 'name' is column 1

            int image_column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id);
            var imageView = (ImageView)view;
            int id = cursor.GetInt(image_column_index);

            Bitmap bm = MediaStore.Images.Thumbnails.GetThumbnail(context.ContentResolver, id, ThumbnailKind.MicroKind, null);
            //Bitmap bm = MediaStore.Images.Media.GetBitmap(context.ContentResolver, id);

            BitmapDrawable drawable = imageView.Drawable as BitmapDrawable;

            if (drawable != null && drawable.Bitmap != null)
            {
                //drawable.Bitmap.Dispose();
                drawable.Bitmap.Recycle();
            }

            imageView.SetImageBitmap(bm);
        }
Exemplo n.º 34
0
		internal static IEnumerable<Contact> GetContacts (ICursor cursor, bool rawContacts, ContentResolver content, Resources resources, int batchSize)
		{
			if (cursor == null)
				yield break;

			string column = (rawContacts)
								? ContactsContract.RawContactsColumns.ContactId
								: ContactsContract.ContactsColumns.LookupKey;

			string[] ids = new string[batchSize];
			int columnIndex = cursor.GetColumnIndex (column);

			HashSet<string> uniques = new HashSet<string>();

			int i = 0;
			while (cursor.MoveToNext())
			{
				if (i == batchSize)
				{
					i = 0;
					foreach (Contact c in GetContacts (rawContacts, content, resources, ids))
						yield return c;
				}

				string id = cursor.GetString (columnIndex);
				if (uniques.Contains (id))
					continue;

				uniques.Add (id);
				ids[i++] = id;
			}

			if (i > 0)
			{
				foreach (Contact c in GetContacts (rawContacts, content, resources, ids.Take(i).ToArray()))
					yield return c;
			}
		}
Exemplo n.º 35
0
		internal static Organization GetOrganization (ICursor c, Resources resources)
		{
			Organization o = new Organization();
			o.Name = c.GetString (OrganizationData.Company);
			o.ContactTitle = c.GetString (OrganizationData.Title);

			OrganizationDataKind d = (OrganizationDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			o.Type = d.ToOrganizationType();
			o.Label = (d != OrganizationDataKind.Custom)
						? OrganizationData.GetTypeLabel (resources, d, String.Empty)
						: c.GetString (CommonColumns.Label);

			return o;
		}
Exemplo n.º 36
0
		internal static Email GetEmail (ICursor c, Resources resources)
		{
			Email e = new Email();
			e.Address = c.GetString (ContactsContract.DataColumns.Data1);

			EmailDataKind ekind = (EmailDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			e.Type = ekind.ToEmailType();
			e.Label = (ekind != EmailDataKind.Custom)
						? ContactsContract.CommonDataKinds.Email.GetTypeLabel (resources, ekind, String.Empty)
						: c.GetString (CommonColumns.Label);

			return e;
		}
Exemplo n.º 37
0
		internal static Phone GetPhone (ICursor c, Resources resources)
		{
			Phone p = new Phone();
			p.Number = GetString (c, ContactsContract.CommonDataKinds.Phone.Number);

			PhoneDataKind pkind = (PhoneDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			p.Type = pkind.ToPhoneType();
			p.Label = (pkind != PhoneDataKind.Custom)
						? ContactsContract.CommonDataKinds.Phone.GetTypeLabel (resources, pkind, String.Empty)
						: c.GetString (CommonColumns.Label);

			return p;
		}
Exemplo n.º 38
0
		internal static Address GetAddress (ICursor c, Resources resources)
		{
			Address a = new Address();
			a.Country = c.GetString (StructuredPostal.Country);
			a.Region = c.GetString (StructuredPostal.Region);
			a.City = c.GetString (StructuredPostal.City);
			a.PostalCode = c.GetString (StructuredPostal.Postcode);

			AddressDataKind kind = (AddressDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			a.Type = kind.ToAddressType();
			a.Label = (kind != AddressDataKind.Custom)
						? StructuredPostal.GetTypeLabel (resources, kind, String.Empty)
						: c.GetString (CommonColumns.Label);

			string street = c.GetString (StructuredPostal.Street);
			string pobox = c.GetString (StructuredPostal.Pobox);
			if (street != null)
				a.StreetAddress = street;
			if (pobox != null)
			{
				if (street != null)
					a.StreetAddress += Environment.NewLine;

				a.StreetAddress += pobox;
			}
			return a;
		}
Exemplo n.º 39
0
        public System.String PhonesByCursor(ICursor cur)
        {
            System.String phones="";
            int id = cur.GetInt(cur.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
            if (System.Int16.Parse(cur.GetString(cur.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.HasPhoneNumber))) > 0)
            {
                var loader = new CursorLoader (_context, ContactsContract.CommonDataKinds.Phone.ContentUri,null,ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId +" = "+id,null, null);
                ICursor pCur;
                pCur = (ICursor)loader.LoadInBackground();

            while (pCur.MoveToNext())
                {
                    phones+=pCur.GetString(pCur.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Data))+"\r\n";
                }
                pCur.Close();
            }
            return phones;
        }
Exemplo n.º 40
0
		internal static Contact GetContact (bool rawContact, ContentResolver content, Resources resources, ICursor cursor)
		{
			string id = (rawContact)
							? cursor.GetString (cursor.GetColumnIndex (ContactsContract.RawContactsColumns.ContactId))
							: cursor.GetString (cursor.GetColumnIndex (ContactsContract.ContactsColumns.LookupKey));

			Contact contact = new Contact (id, !rawContact, content);
			contact.DisplayName = GetString (cursor, ContactsContract.ContactsColumns.DisplayName);

			FillContactExtras (rawContact, content, resources, id, contact);

			return contact;
		}
Exemplo n.º 41
0
            public CursorContact(ICursor cur)
            {
                var idField = cur.GetColumnIndex(ContactsContract.PhoneLookup.InterfaceConsts.Id);
                var nameField = cur.GetColumnIndex(ContactsContract.PhoneLookup.InterfaceConsts.DisplayName);
                var hasField = cur.GetColumnIndex(ContactsContract.PhoneLookup.InterfaceConsts.HasPhoneNumber);

                Id = cur.GetString(idField);
                DisplayName = cur.GetString(nameField);
                HasPhone = cur.GetString(hasField) != "0";
            }
 /// <summary>
 /// Cursors to episode.
 /// </summary>
 /// <returns>The to episode.</returns>
 /// <param name='cursor'>Cursor.</param>
 private Episode cursorToEpisode(ICursor cursor)
 {
     Episode episode = new Episode();
       episode.Description = cursor.GetString(cursor.GetColumnIndex(Episode.COL_DESCRIPTION));
       episode.MygpoLink = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Episode.COL_MYGPO_LINK)));
       episode.PodcastTitle = cursor.GetString(cursor.GetColumnIndex(Episode.COL_PODCAST_TITLE));
       episode.PodcastUrl = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Episode.COL_PODCAST_URL)));
       episode.Released = DateTime.Parse(cursor.GetString(cursor.GetColumnIndex(Episode.COL_RELEASED)));
       episode.Status = (Episode.EpisodeStatus)Enum.Parse(typeof(Episode.EpisodeStatus), cursor.GetString(cursor.GetColumnIndex(Episode.COL_STATUS)));
       episode.Title = cursor.GetString(cursor.GetColumnIndex(Episode.COL_TITLE));
       episode.Url = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Episode.COL_URL)));
       episode.Website = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Episode.COL_WEBSITE)));
       episode.PlayerPosition = cursor.GetInt(cursor.GetColumnIndex(Episode.COL_PLAYER_POSITION));
       episode.Duration = cursor.GetInt(cursor.GetColumnIndex(Episode.COL_DURATION));
       return episode;
 }
        //When an item of the list is clicked, it reaches to the SQLite database and retrieves the information associated
        protected void OnListItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e)
        {
            selected = cursor.GetString (1);
            Toast.MakeText (this, selected, ToastLength.Short).Show();
            //			var obj = MyList.Adapter.GetItem(e.Position);
            //			var text = obj.ToString ();
            //			//var curs = (ICursor)obj;
            //			//var text = curs.GetString(1); // 'name' is column 1
            //			Android.Widget.Toast.MakeText(this, text, Android.Widget.ToastLength.Short).Show();
            //			System.Console.WriteLine("Clicked on " + text);
            SetContentView (Resource.Layout.Character);

            TextView name = FindViewById<TextView> (Resource.Id.Name);
            TextView description = FindViewById<TextView> (Resource.Id.Description);
            ImageView picture = FindViewById<ImageView> (Resource.Id.Picture);

            //SQL commands to retrieve information regarding the clicked item from the list
            cursor = vdb.ReadableDatabase.RawQuery("SELECT name FROM superheroes WHERE name = '" + selected + "'", null);
            cursor.MoveToFirst (); //Edited based on suggestion from SAM
            string strName = cursor.GetString(cursor.GetColumnIndex("name"));
            name.Text = strName;
            cursor = vdb.ReadableDatabase.RawQuery("SELECT description FROM superheroes WHERE name = '" + selected + "'", null);
            cursor.MoveToFirst (); //Edited based on suggestion from SAM
            strName = cursor.GetString(cursor.GetColumnIndex("description"));
            description.Text = strName;

            //Cleaning the selected string to get the matching image for the selected character
            selected = selected.Replace (" ", "");
            selected = selected.Replace ("-", "");
            String uri = "drawable/" + selected;
            //Toast.MakeText (this, uri, ToastLength.Short).Show();
            int imageResource = 0;
            imageResource= (int)typeof(Resource.Drawable).GetField(selected).GetValue(null);
            //int imageResource = Resources.GetIdentifier (uri, null, PackageName);
            //Toast.MakeText (this, imageResource.ToString(), ToastLength.Short).Show();
            Android.Graphics.Drawables.Drawable res = Resources.GetDrawable (imageResource);
            //int drawableID = Resources.GetInteger(Resources.GetIdentifier(selected, "drawable", PackageName));
            picture.SetImageDrawable (res);

            //Clicking the picture will go back to the main menu
            picture.Click += delegate {
                // Set our view from the "main" layout resource
                SetContentView (Resource.Layout.Main);

                MyList = FindViewById<ListView> (Resource.Id.myListView);

                // create the cursor
                vdb = new SuperheroesDatabase (this);
                cursor = vdb.ReadableDatabase.RawQuery ("SELECT * FROM Superheroes", null);
                StartManagingCursor (cursor);

                // which columns map to which layout controls
                string[] fromColumns = new string[] { "name" };
                int[] toControlIds = new int [] { Android.Resource.Id.Text1 };

                // use a SimpleCursorAdapter
                MyList.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIds);

                MyList.ItemClick += OnListItemClick;

            };

            ImageButton Menu;
            Menu = FindViewById<ImageButton> (Resource.Id.imageButton1);
            Menu.Click += delegate {
                // Set our view from the "main" layout resource
                SetContentView (Resource.Layout.Main);

                MyList = FindViewById<ListView> (Resource.Id.myListView);

                // create the cursor
                vdb = new SuperheroesDatabase (this);
                cursor = vdb.ReadableDatabase.RawQuery ("SELECT * FROM Superheroes", null);
                StartManagingCursor (cursor);

                // which columns map to which layout controls
                string[] fromColumns = new string[] { "name" };
                int[] toControlIds = new int [] { Android.Resource.Id.Text1 };

                // use a SimpleCursorAdapter
                MyList.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIds);

                MyList.ItemClick += OnListItemClick;

            };

            Button Back;
            Back = FindViewById<Button> (Resource.Id.btnMenu);
            Back.Click += delegate {
                // Set our view from the "main" layout resource
                SetContentView (Resource.Layout.Main);

                MyList = FindViewById<ListView> (Resource.Id.myListView);

                // create the cursor
                vdb = new SuperheroesDatabase(this);
                cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM Superheroes", null);
                StartManagingCursor(cursor);

                // which columns map to which layout controls
                string[] fromColumns = new string[] { "name" };
                int[] toControlIds = new int [] {Android.Resource.Id.Text1};

                // use a SimpleCursorAdapter
                MyList.Adapter = new SimpleCursorAdapter(this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIds);

                MyList.ItemClick += OnListItemClick;

            };
        }
 /// <summary>
 /// Cursors to subscription.
 /// </summary>
 /// <returns>The to subscription.</returns>
 /// <param name='cursor'>Cursor.</param>
 private Subscription cursorToSubscription(ICursor cursor)
 {
     Subscription subscription = new Subscription();
       subscription.Description = cursor.GetString(cursor.GetColumnIndex(Subscription.COL_DESCRIPTION));
       subscription.LogoUrl = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Subscription.COL_LOGO_URL)));
       subscription.MygpoLink = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Subscription.COL_MYGPO_LINK)));
       subscription.PositionLastWeek = cursor.GetInt(cursor.GetColumnIndex(Subscription.COL_POSITION_LAST_WEEK));
       subscription.ScaledLogoUrl = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Subscription.COL_SCALED_LOGO_URL)));
       subscription.Subscribers = cursor.GetInt(cursor.GetColumnIndex(Subscription.COL_SUBSCRIBERS));
       subscription.SubscribersLastWeek = cursor.GetInt(cursor.GetColumnIndex(Subscription.COL_SUBSRIBERS_LAST_WEEK));
       subscription.Title = cursor.GetString(cursor.GetColumnIndex(Subscription.COL_TITLE));
       subscription.Url = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Subscription.COL_URL)));
       subscription.Website = stringToUrl(cursor.GetString(cursor.GetColumnIndex(Subscription.COL_WEBSITE)));
       return subscription;
 }
Exemplo n.º 45
0
		private static void FillContactWithRow (Resources resources, Contact contact, ICursor c)
		{
			string dataType = c.GetString (c.GetColumnIndex (ContactsContract.DataColumns.Mimetype));
			switch (dataType)
			{
				case ContactsContract.CommonDataKinds.Nickname.ContentItemType:
					contact.Nickname = c.GetString (c.GetColumnIndex (ContactsContract.CommonDataKinds.Nickname.Name));
					break;

				case StructuredName.ContentItemType:
					contact.Prefix = c.GetString (StructuredName.Prefix);
					contact.FirstName = c.GetString (StructuredName.GivenName);
					contact.MiddleName = c.GetString (StructuredName.MiddleName);
					contact.LastName = c.GetString (StructuredName.FamilyName);
					contact.Suffix = c.GetString (StructuredName.Suffix);
					break;

				case ContactsContract.CommonDataKinds.Phone.ContentItemType:
					contact.phones.Add (GetPhone (c, resources));
					break;

				case ContactsContract.CommonDataKinds.Email.ContentItemType:
					contact.emails.Add (GetEmail (c, resources));
					break;

				case ContactsContract.CommonDataKinds.Note.ContentItemType:
					contact.notes.Add (GetNote (c, resources));
					break;

				case ContactsContract.CommonDataKinds.Organization.ContentItemType:
					contact.organizations.Add (GetOrganization (c, resources));
					break;

				case StructuredPostal.ContentItemType:
					contact.addresses.Add (GetAddress (c, resources));
					break;

				case InstantMessaging.ContentItemType:
					contact.instantMessagingAccounts.Add (GetImAccount (c, resources));
					break;

				case WebsiteData.ContentItemType:
					contact.websites.Add (GetWebsite (c, resources));
					break;

				case Relation.ContentItemType:
					contact.relationships.Add (GetRelationship (c, resources));
					break;
			}
		}
Exemplo n.º 46
0
 public override void BindView(View view, Context context, ICursor cursor)
 {
     view.FindViewById<TextView>(Resource.Id.title).Text =
         cursor.GetString(cursor.GetColumnIndex(NoteDatabaseConstants.TitleColumn));
 }
Exemplo n.º 47
0
		internal static Relationship GetRelationship (ICursor c, Resources resources)
		{
			Relationship r = new Relationship { Name = c.GetString (Relation.Name) };

			RelationDataKind rtype = (RelationDataKind)c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			switch (rtype)
			{
				case RelationDataKind.DomesticPartner:
				case RelationDataKind.Spouse:
				case RelationDataKind.Friend:
					r.Type = RelationshipType.SignificantOther;
					break;

				case RelationDataKind.Child:
					r.Type = RelationshipType.Child;
					break;

				default:
					r.Type = RelationshipType.Other;
					break;
			}

			return r;
		}
Exemplo n.º 48
0
		internal static InstantMessagingAccount GetImAccount (ICursor c, Resources resources)
		{
			InstantMessagingAccount ima = new InstantMessagingAccount();
			ima.Account = c.GetString (CommonColumns.Data);

			//IMTypeDataKind imKind = (IMTypeDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type));
			//ima.Type = imKind.ToInstantMessagingType();
			//ima.Label = InstantMessaging.GetTypeLabel (resources, imKind, c.GetString (CommonColumns.Label));

			IMProtocolDataKind serviceKind = (IMProtocolDataKind) c.GetInt (c.GetColumnIndex (InstantMessaging.Protocol));
			ima.Service = serviceKind.ToInstantMessagingService();
			ima.ServiceLabel = (serviceKind != IMProtocolDataKind.Custom)
								? InstantMessaging.GetProtocolLabel (resources, serviceKind, String.Empty)
								: c.GetString (InstantMessaging.CustomProtocol);

			return ima;
		}
 /// <summary>
 /// Cursors to device.
 /// </summary>
 /// <returns>The to device.</returns>
 /// <param name='cursor'>Cursor.</param>
 private Device cursorToDevice(ICursor cursor)
 {
     Device device = new Device();
       device.Id            = cursor.GetString(cursor.GetColumnIndex(Device.COL_ID));
       device.Caption       = cursor.GetString(cursor.GetColumnIndex(Device.COL_CAPTION));
       device.Subscriptions = cursor.GetInt(cursor.GetColumnIndex(Device.COL_SUBSCRIPTIONS));
       device.Type          = (Device.DeviceType)Enum.Parse(typeof(Device.DeviceType),cursor.GetString(cursor.GetColumnIndex(Device.COL_TYPE)));
       return device;
 }
Exemplo n.º 50
0
			public override void BindView (View view, Context context, ICursor cursor)
			{
				TextView tv = (TextView)view;
				int textIndex = cursor.GetColumnIndex (SearchManager.SuggestColumnText1);
				tv.Text = cursor.GetString (textIndex);
			}