Search Results

Search found 40 results on 2 pages for 'contentresolver'.

Page 1/2 | 1 2  | Next Page >

  • What's the easiest way to sort a ContentResolver query by custom order?

    - by Pentium10
    I am faceing a problem where I need to sort my ContentResolver in a custom order. Take for example Contact Groups, you can define and manage them using Android's data database. But if you query this, you are limited to do order by on the name of the group only or id. In my scenarion I need to sort them in an order (other than alphabetic) that I've stored in my database. Take for example this example: Colleagues Excluded Family Friends But the order I want them to display is: Family Colleagues Friends Excluded So how would you accomplish this task?

    Read the article

  • onPerformSync() is not triggered after ContentResolver.requestSync() call

    - by mark
    I am trying to implement sync adaptor, I have followed This guide. But onPerformSync() is not triggered after ContentResolver.requestSync() call . I have also tried some other tutorials and tried to run their code, but still same issue. Please tell me does I need to do some extra configuration for this. My code of triggering sync operation is as folows : Account newAccount = new Account(GlobalInfo.ACCOUNT, GlobalInfo.ACCOUNT_TYPE); AccountManager accountManager = (AccountManager) this.getSystemService(ACCOUNT_SERVICE); accountManager.addAccountExplicitly(newAccount, null, null); ContentResolver.requestSync(newAccount,GlobalInfo.AUTHORITY, Bundle.EMPTY); Please guide me to solve this issue. EDIT : Accounted created (in Settings - Accounts and Sync settings) by above code showing sync is off

    Read the article

  • How to get contacts in order of their upcoming birthdays?

    - by Pentium10
    I have code to read contact details and to read birthdays. But how do I get a list of contacts in order of their upcoming birthday? For a single contact identified by id, I get details and birthday like this: Cursor c = null; try { Uri uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, id); c = ctx.getContentResolver().query(uri, null, null, null, null); if (c != null) { if (c.moveToFirst()) { DatabaseUtils.cursorRowToContentValues(c, data); } } c.close(); // read birthday c = ctx.getContentResolver() .query( Data.CONTENT_URI, new String[] { Event.DATA }, Data.CONTACT_ID + "=" + id + " AND " + Data.MIMETYPE + "= '" + Event.CONTENT_ITEM_TYPE + "' AND " + Event.TYPE + "=" + Event.TYPE_BIRTHDAY, null, Data.DISPLAY_NAME); if (c != null) { try { if (c.moveToFirst()) { this.setBirthday(c.getString(0)); } } finally { c.close(); } } return super.load(id); } catch (Exception e) { Log.v(TAG(), e.getMessage(), e); e.printStackTrace(); return false; } finally { if (c != null) c.close(); } and the code to read all contacts is: public Cursor getList() { // Get the base URI for the People table in the Contacts content // provider. Uri contacts = ContactsContract.Contacts.CONTENT_URI; // Make the query. ContentResolver cr = ctx.getContentResolver(); // Form an array specifying which columns to return. String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; Cursor managedCursor = cr.query(contacts, projection, null, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); return managedCursor; }

    Read the article

  • How can I update the album art path using contentResolver?

    - by Ungureanu Liviu
    Hi! I want to update/insert a new image for an album in MediaStore but i can't get it work.. This is my code: public void updateAlbumImage(String path, int albumID) { ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Albums.ALBUM_ART, path); int n = contentResolver.update(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, values, MediaStore.Audio.Albums.ALBUM_ID + "=" + albumID, null); Log.e(TAG, "updateAlbumImage(" + path + ", " + albumID + "): " + n); } The error is: 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): java.lang.UnsupportedOperationException: Unknown or unsupported URL: content://media/external/audio/albums 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:131) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:111) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at android.content.ContentProviderProxy.update(ContentProviderNative.java:405) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at android.content.ContentResolver.update(ContentResolver.java:554) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at com.liviu.app.smpp.managers.AudioManager.updateAlbumImage(AudioManager.java:563) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at com.liviu.app.smpp.ShowAlbumsActivity.saveImageFile(ShowAlbumsActivity.java:375) 03-24 03:09:46.323: ERROR/AndroidRuntime(5319): at com.liviu.app.smpp.ShowAlbumsActivity.onClick(ShowAlbumsActivity.java:350) Thank you!

    Read the article

  • How to get contacts in order of they upcoming birthdays?

    - by Pentium10
    I have code to read contacts details and to read birthday. But how do I get a list of contacts in order of they upcoming birthday? For a single contact identified by id I get details and birthday like this. Cursor c = null; try { Uri uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, id); c = ctx.getContentResolver().query(uri, null, null, null, null); if (c != null) { if (c.moveToFirst()) { DatabaseUtils.cursorRowToContentValues(c, data); } } c.close(); // read birthday c = ctx.getContentResolver() .query( Data.CONTENT_URI, new String[] { Event.DATA }, Data.CONTACT_ID + "=" + id + " AND " + Data.MIMETYPE + "= '" + Event.CONTENT_ITEM_TYPE + "' AND " + Event.TYPE + "=" + Event.TYPE_BIRTHDAY, null, Data.DISPLAY_NAME); if (c != null) { try { if (c.moveToFirst()) { this.setBirthday(c.getString(0)); } } finally { c.close(); } } return super.load(id); } catch (Exception e) { Log.v(TAG(), e.getMessage(), e); e.printStackTrace(); return false; } finally { if (c != null) c.close(); }

    Read the article

  • Android: getting thumbnails from specific location on sd card

    - by dykzei
    AFAIK accessing thumbnails for images via MediaStore.Images.Thumbnails would generate thumbnails at first attempt, and that's what i need to perform against specific location on sd card. The question is how to make valid URI to content under specific folder? All answers i can find use just MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI as uri to make managedQuery. And result of it is Cursor that points to all sdcard images, while none examples can be found on how to access only specific folder.

    Read the article

  • [Android]problem when delete contacts,please help me

    - by Enchor
    I have been working with Android contacts. I am able to show them, update but when I want to delete any, it is not deleted completely. In Contacts application is shown as (Unknown) without any data. Here is my example: ArrayList ops = new ArrayList(); ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI) .withSelection(Data.CONTACT_ID + "=?", new String[]{selectedid}) .build()); getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); Should I do anything else to delete contact entirely? It seems that these code delete info in table ContactsContract.Data but it does not delete element related in table ContactsContract.Contacts or ContactsContract.RawContacts.how can i do to delete an contact completely? ============================================================================ also, i tried deprecated method. It dose work, but i do not want to do so. Here is the sample code: ContentResolver contentResolver = m_cContent.getContentResolver(); contentResolver.delete(People.CONTENT_URI, People.NAME + "=?", new String[] { SelectedName }); and if i modify this code to ContentResolver contentResolver = m_cContent.getContentResolver(); contentResolver.delete(ContactsContract.Contacts, ContactsContract.Contacts._ID + "=?", new String[] { Selectedid }); It has no effect. Does it mean that one can only delete a contact by name instead of by its id? What on earth can i do to delete contact? Thanks, Enchor

    Read the article

  • Android - How do I load a contact Photo?

    - by PaulH
    I'm having trouble loading a photo for a contact in Android. I've googled for an answer, but so far have come up empty. Does anyone have an example of querying for a Contact, then loading the Photo? So, given a contactUri which comes from an Activity result called using startActivityForResult(new Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI),PICK_CONTACT_REQUEST) is: content://com.android.contacts/data/1557 The loadContact(..) works fine. However when I call the getPhoto(...) method, I get a null value for the photo InputStream. It is also confusing because the URI values are different. The contactPhotoUri evaluates to: content://com.android.contacts/contacts/1557 See the comments inline in the code below. class ContactAccessor { /** * Retrieves the contact information. */ public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) { //contactUri --> content://com.android.contacts/data/1557 ContactInfo contactInfo = new ContactInfo(); // Load the display name for the specified person Cursor cursor = contentResolver.query(contactUri, new String[]{Contacts._ID, Contacts.DISPLAY_NAME, Phone.NUMBER, Contacts.PHOTO_ID}, null, null, null); try { if (cursor.moveToFirst()) { contactInfo.setId(cursor.getLong(0)); contactInfo.setDisplayName(cursor.getString(1)); contactInfo.setPhoneNumber(cursor.getString(2)); } } finally { cursor.close(); } return contactInfo; // <-- returns info for contact } public Bitmap getPhoto(ContentResolver contentResolver, Long contactId) { Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // contactPhotoUri --> content://com.android.contacts/contacts/1557 InputStream photoDataStream = Contacts.openContactPhotoInputStream(contentResolver,contactPhotoUri); // <-- always null Bitmap photo = BitmapFactory.decodeStream(photoDataStream); return photo; } public class ContactInfo { private long id; private String displayName; private String phoneNumber; private Uri photoUri; public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneNumber() { return phoneNumber; } public Uri getPhotoUri() { return this.photoUri; } public void setPhotoUri(Uri photoUri) { this.photoUri = photoUri; } public long getId() { return this.id; } public void setId(long id) { this.id = id; } } } Clearly, I'm doing something wrong here, but I can't seem to figure out what the problem is. Thanks.

    Read the article

  • File name containing more than 16 characters inside parentheses failing

    - by Tom anMoney
    I am generating file names that contain a timestamp in the following format: "base_name (yyyy-mm-dd hhmmss).ext" This seems to cause a problem on Android. Here's my log: /storage/sdcard0/anMoney/transfer/Net worth over time _ Forecast (2012-11-19 110550).pdf E/Gmail (11802): java.io.FileNotFoundException: /storage/sdcard0/myapp/transfer/Net worth over time _ Forecast (2012-11-19 110550).pdf: open failed: ENOENT (No such file or directory) E/Gmail (11802): at libcore.io.IoBridge.open(IoBridge.java:416) E/Gmail (11802): at java.io.FileInputStream.<init>(FileInputStream.java:78) E/Gmail (11802): at java.io.FileInputStream.<init>(FileInputStream.java:105) E/Gmail (11802): at android.content.ContentResolver.openInputStream(ContentResolver.java:445) E/Gmail (11802): at com.google.android.gm.provider.MailEngine.cacheAttachment(MailEngine.java:3054) E/Gmail (11802): at com.google.android.gm.provider.MailEngine.sendOrSaveDraft(MailEngine.java:2746) E/Gmail (11802): at com.google.android.gm.provider.MailProvider.sendOrSaveDraft(MailProvider.java:477) E/Gmail (11802): at com.google.android.gm.provider.MailProvider.insert(MailProvider.java:534) E/Gmail (11802): at android.content.ContentProvider$Transport.insert(ContentProvider.java:201) E/Gmail (11802): at android.content.ContentResolver.insert(ContentResolver.java:864) E/Gmail (11802): at com.google.android.gm.provider.Gmail$MessageModification.sendOrSaveNewMessage(Gmail.java:3576) E/Gmail (11802): at com.google.android.gm.ComposeActivity$SendOrSaveTask$1.onInitializationComplete(ComposeActivity.java:1765) E/Gmail (11802): at com.google.android.gm.provider.MailEngine$5.run(MailEngine.java:1006) E/Gmail (11802): at android.os.Handler.handleCallback(Handler.java:615) E/Gmail (11802): at android.os.Handler.dispatchMessage(Handler.java:92) E/Gmail (11802): at android.os.Looper.loop(Looper.java:137) E/Gmail (11802): at android.os.HandlerThread.run(HandlerThread.java:60) E/Gmail (11802): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) Now, if I trim the file name to have only 16 characters within the parentheses, everything is working as expected. I am able to send the file as a GMail attachment. The following file name is working fine: /storage/sdcard0/myapp/transfer/Net worth over time _ Forecast (2012-11-19 11070).pdf I tried the following troubleshooting: It's not the overall length of the file name, as if I shorten the base name, the same behavior remains It's not GMail, uploading the file to Google Drive fails similarly 16 characters inside the parentheses work, but not 17 It's not the space character inside the parentheses that causes the issue, as I replaced it with a dash and it's the same problem. Anybody has any ideas on what's going on here?

    Read the article

  • Reg : Contact changes in Android

    - by Laxman
    Hi, I am using ContentObserver on contacts. But here my problem is atleast once i have to launch my application other wise i am unable to get notification chages. My code like this ContactsContentObserver cco = new ContactsContentObserver(handler); ContentResolver contentResolver = getContentResolver(); contentResolver.registerContentObserver(RawContacts.CONTENT_URI, true, cco); } private class ContactsContentObserver extends ContentObserver { public ContactsContentObserver(Handler h) { super(h); } public void onChange(boolean selfChange) { System.out.println("##########SOMEBODAY CHANGED ANYTHING AT THE CONTACTS"); Toast.makeText(getApplication(),"####Updated####",Toast.LENGTH_LONG).show(); } .... Adv thanks. u can contact on [email protected]

    Read the article

  • Media query from a specific folder

    - by sensei
    I would like to understand how I can use a cursor to jpg files in a folder specified in the sdcard. I'm trying to select with a cursor the jpg files in a specific folder, and I tried this: This is the code: public static Uri getRandomImage(ContentResolver resolver) { String[] projection = new String[] { BaseColumns._ID, }; String folder = "/sdcard/DCIM/Wallpaper/"; folder = folder + "%"; Uri uri = Media.EXTERNAL_CONTENT_URI; String[] whereArgs = new String[]{folder}; Cursor cursor = resolver.query(uri, projection, null, whereArgs, MediaColumns._ID); if (cursor == null || cursor.getCount() <= 0) { return null; } cursor.moveToPosition(new Random().nextInt(cursor.getCount())); return Uri.withAppendedPath(uri, cursor.getString(0)); } but this code gives me error here is the logcat: E/AndroidRuntime(11986): FATAL EXCEPTION: main E/AndroidRuntime(11986): android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x26a490 E/AndroidRuntime(11986): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158) E/AndroidRuntime(11986): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114) E/AndroidRuntime(11986): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330) E/AndroidRuntime(11986): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366) E/AndroidRuntime(11986): at android.content.ContentResolver.query(ContentResolver.java:245) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.SelectImagePreference.getRandomImage(SelectImagePreference.java:126) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.TileView.newGame(TileView.java:156) E/AndroidRuntime(11986): at it.bisemanuDEV.slidepuzzle.SlidePuzzleActivity.onOptionsItemSelected(SlidePuzzleActivity.java:377) E/AndroidRuntime(11986): at android.app.Activity.onMenuItemSelected(Activity.java:2762) E/AndroidRuntime(11986): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730) E/AndroidRuntime(11986): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143) E/AndroidRuntime(11986): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855) E/AndroidRuntime(11986): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532) E/AndroidRuntime(11986): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122) E/AndroidRuntime(11986): at android.view.View$PerformClick.run(View.java:8819) E/AndroidRuntime(11986): at android.os.Handler.handleCallback(Handler.java:603) E/AndroidRuntime(11986): at android.os.Handler.dispatchMessage(Handler.java:92) E/AndroidRuntime(11986): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime(11986): at android.app.ActivityThread.main(ActivityThread.java:4627) E/AndroidRuntime(11986): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(11986): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime(11986): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime(11986): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) E/AndroidRuntime(11986): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • NullPointerException when linking to Service that uses ContentProvider

    - by Danny Chia
    H.i everyone, this is my first post here! Anyways, I'm trying to write a "todo list" application. It stores the data in a ContentProvider, which is accessed via a Service. However, my app crashes at launch. My code is below: Manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.examples.todolist" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="True"> <activity android:name=".ToDoList" android:label="@string/app_name" android:theme="@style/ToDoTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="TodoService"/> <provider android:name="TodoProvider" android:authorities="com.examples.provider.todolist" /> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> ToDoList.java: package com.examples.todolist; import com.examples.todolist.TodoService.LocalBinder; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class ToDoList extends Activity { static final private int ADD_NEW_TODO = Menu.FIRST; static final private int REMOVE_TODO = Menu.FIRST + 1; private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY"; private boolean addingNew = false; private ArrayList<ToDoItem> todoItems; private ListView myListView; private EditText myEditText; private ToDoItemAdapter aa; int entries = 0; int notifs = 0; //ToDoDBAdapter toDoDBAdapter; Cursor toDoListCursor; TodoService mService; boolean mBound = false; /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText); todoItems = new ArrayList<ToDoItem>(); int resID = R.layout.todolist_item; aa = new ToDoItemAdapter(this, resID, todoItems); myListView.setAdapter(aa); myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { ToDoItem newItem = new ToDoItem(myEditText.getText().toString(), 0); mService.insertTask(newItem); updateArray(); myEditText.setText(""); entries++; Toast.makeText(ToDoList.this, "Entry added", Toast.LENGTH_SHORT).show(); aa.notifyDataSetChanged(); cancelAdd(); return true; } return false; } }); registerForContextMenu(myListView); restoreUIState(); populateTodoList(); } private void populateTodoList() { // Get all the todo list items from the database. toDoListCursor = mService. getAllToDoItemsCursor(); startManagingCursor(toDoListCursor); // Update the array. updateArray(); Toast.makeText(this, "Todo list retrieved", Toast.LENGTH_SHORT).show(); } private void updateArray() { toDoListCursor.requery(); todoItems.clear(); if (toDoListCursor.moveToFirst()) do { String task = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_TASK)); long created = toDoListCursor.getLong(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_CREATION_DATE)); int taskid = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID)); ToDoItem newItem = new ToDoItem(task, new Date(created), taskid); todoItems.add(0, newItem); } while(toDoListCursor.moveToNext()); aa.notifyDataSetChanged(); } private void restoreUIState() { // Get the activity preferences object. SharedPreferences settings = getPreferences(0); // Read the UI state values, specifying default values. String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); // Restore the UI to the previous state. if (adding) { addNewItem(); myEditText.setText(text); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if (savedInstanceState != null) if (savedInstanceState.containsKey(SELECTED_INDEX_KEY)) pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); myListView.setSelection(pos); } @Override protected void onPause() { super.onPause(); // Get the activity preferences object. SharedPreferences uiState = getPreferences(0); // Get the preferences editor. SharedPreferences.Editor editor = uiState.edit(); // Add the UI state preference values. editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); editor.putBoolean(ADDING_ITEM_KEY, addingNew); // Commit the preferences. editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Create and add new menu items. MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new); MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); // Assign icons itemAdd.setIcon(R.drawable.add_new_item); itemRem.setIcon(R.drawable.remove_item); // Allocate shortcuts to each of them. itemAdd.setShortcut('0', 'a'); itemRem.setShortcut('1', 'r'); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); int idx = myListView.getSelectedItemPosition(); String removeTitle = getString(addingNew ? R.string.cancel : R.string.remove); MenuItem removeItem = menu.findItem(REMOVE_TODO); removeItem.setTitle(removeTitle); removeItem.setVisible(addingNew || idx > -1); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Selected To Do Item"); menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int index = myListView.getSelectedItemPosition(); switch (item.getItemId()) { case (REMOVE_TODO): { if (addingNew) { cancelAdd(); } else { removeItem(index); } return true; } case (ADD_NEW_TODO): { addNewItem(); return true; } } return false; } @Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); switch (item.getItemId()) { case (REMOVE_TODO): { AdapterView.AdapterContextMenuInfo menuInfo; menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int index = menuInfo.position; removeItem(index); return true; } } return false; } @Override public void onDestroy() { super.onDestroy(); } private void cancelAdd() { addingNew = false; myEditText.setVisibility(View.GONE); } private void addNewItem() { addingNew = true; myEditText.setVisibility(View.VISIBLE); myEditText.requestFocus(); } private void removeItem(int _index) { // Items are added to the listview in reverse order, so invert the index. //toDoDBAdapter.removeTask(todoItems.size()-_index); ToDoItem item = todoItems.get(_index); final long selectedId = item.getTaskId(); mService.removeTask(selectedId); entries--; Toast.makeText(this, "Entry deleted", Toast.LENGTH_SHORT).show(); updateArray(); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, TodoService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; public class TimedToast extends AsyncTask<Long, Integer, Integer> { @Override protected Integer doInBackground(Long... arg0) { if (notifs < 15) { try { Toast.makeText(ToDoList.this, entries + " entries left", Toast.LENGTH_SHORT).show(); notifs++; Thread.sleep(20000); } catch (InterruptedException e) { } } return 0; } } } TodoService.java: package com.examples.todolist; import android.app.Service; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Binder; import android.os.IBinder; public class TodoService extends Service { private final IBinder mBinder = new LocalBinder(); @Override public IBinder onBind(Intent arg0) { return mBinder; } public class LocalBinder extends Binder { TodoService getService() { return TodoService.this; } } public void insertTask(ToDoItem _task) { ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_CREATION_DATE, _task.getCreated().getTime()); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.insert(TodoProvider.CONTENT_URI, values); } public void updateTask(ToDoItem _task) { long tid = _task.getTaskId(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.update(TodoProvider.CONTENT_URI, values, TodoProvider.KEY_ID + "=" + tid, null); } public void removeTask(long tid) { ContentResolver cr = getContentResolver(); cr.delete(TodoProvider.CONTENT_URI, TodoProvider.KEY_ID + "=" + tid, null); } public Cursor getAllToDoItemsCursor() { ContentResolver cr = getContentResolver(); return cr.query(TodoProvider.CONTENT_URI, null, null, null, null); } } TodoProvider.java: package com.examples.todolist; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class TodoProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.examples.provider.todolist/todo"); @Override public boolean onCreate() { Context context = getContext(); todoHelper dbHelper = new todoHelper(context, DATABASE_NAME, null, DATABASE_VERSION); todoDB = dbHelper.getWritableDatabase(); return (todoDB == null) ? false : true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder tb = new SQLiteQueryBuilder(); tb.setTables(TODO_TABLE); // If this is a row query, limit the result set to the passed in row. switch (uriMatcher.match(uri)) { case TASK_ID: tb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); break; default: break; } // If no sort order is specified sort by date / time String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = KEY_ID; } else { orderBy = sort; } // Apply the query to the underlying database. Cursor c = tb.query(todoDB, projection, selection, selectionArgs, null, null, orderBy); // Register the contexts ContentResolver to be notified if // the cursor result set changes. c.setNotificationUri(getContext().getContentResolver(), uri); // Return a cursor to the query result. return c; } @Override public Uri insert(Uri _uri, ContentValues _initialValues) { // Insert the new row, will return the row number if // successful. long rowID = todoDB.insert(TODO_TABLE, "task", _initialValues); // Return a URI to the newly inserted row on success. if (rowID > 0) { Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(uri, null); return uri; } throw new SQLException("Failed to insert row into " + _uri); } @Override public int delete(Uri uri, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.delete(TODO_TABLE, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.delete(TODO_TABLE, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.update(TODO_TABLE, values, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.update(TODO_TABLE, values, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case TASKS: return "vnd.android.cursor.dir/vnd.examples.task"; case TASK_ID: return "vnd.android.cursor.item/vnd.examples.task"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Create the constants used to differentiate between the different URI // requests. private static final int TASKS = 1; private static final int TASK_ID = 2; private static final UriMatcher uriMatcher; // Allocate the UriMatcher object, where a URI ending in 'tasks' will // correspond to a request for all tasks, and 'tasks' with a // trailing '/[rowID]' will represent a single task row. static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("com.examples.provider.Todolist", "tasks", TASKS); uriMatcher.addURI("com.examples.provider.Todolist", "tasks/#", TASK_ID); } //The underlying database private SQLiteDatabase todoDB; private static final String TAG = "TodoProvider"; private static final String DATABASE_NAME = "todolist.db"; private static final int DATABASE_VERSION = 1; private static final String TODO_TABLE = "todolist"; // Column Names public static final String KEY_ID = "_id"; public static final String KEY_TASK = "task"; public static final String KEY_CREATION_DATE = "date"; public long insertTask(ToDoItem _task) { // Create a new row of values to insert. ContentValues newTaskValues = new ContentValues(); // Assign values for each row. newTaskValues.put(KEY_TASK, _task.getTask()); newTaskValues.put(KEY_CREATION_DATE, _task.getCreated().getTime()); // Insert the row. return todoDB.insert(TODO_TABLE, null, newTaskValues); } public boolean updateTask(long _rowIndex, String _task) { ContentValues newValue = new ContentValues(); newValue.put(KEY_TASK, _task); return todoDB.update(TODO_TABLE, newValue, KEY_ID + "=" + _rowIndex, null) > 0; } public boolean removeTask(long _rowIndex) { return todoDB.delete(TODO_TABLE, KEY_ID + "=" + _rowIndex, null) > 0; } // Helper class for opening, creating, and managing database version control private static class todoHelper extends SQLiteOpenHelper { private static final String DATABASE_CREATE = "create table " + TODO_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_TASK + " TEXT, " + KEY_CREATION_DATE + " INTEGER);"; public todoHelper(Context cn, String name, CursorFactory cf, int ver) { super(cn, name, cf, ver); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE); onCreate(db); } } } I've omitted the other files as I'm sure they are correct. When I run the program, LogCat shows that the NullPointerException occurs in populateTodoList(), at toDoListCursor = mService.getAllToDoItemsCursor(). mService is the Cursor object returned by TodoService. I've added the service to the Manifest file, but I still cannot find out why it's causing an exception. Thanks in advance.

    Read the article

  • Record audio via MediaRecorder

    - by Isuru Madusanka
    I am trying to record audio by MediaRecorder, and I get an error, I tried to change everything and nothing works. Last two hours I try to find the error, I used Log class too and I found out that error occurred when it call recorder.start() method. What could be the problem? public class AudioRecorderActivity extends Activity { MediaRecorder recorder; File audioFile = null; private static final String TAG = "AudioRecorderActivity"; private View startButton; private View stopButton; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startButton = findViewById(R.id.start); stopButton = findViewById(R.id.stop); setContentView(R.layout.main); } public void startRecording(View view) throws IOException{ startButton.setEnabled(false); stopButton.setEnabled(true); File sampleDir = Environment.getExternalStorageDirectory(); try{ audioFile = File.createTempFile("sound", ".3gp", sampleDir); }catch(IOException e){ Toast.makeText(getApplicationContext(), "SD Card Access Error", Toast.LENGTH_LONG).show(); Log.e(TAG, "Sdcard access error"); return; } recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setAudioEncodingBitRate(16); recorder.setAudioSamplingRate(44100); recorder.setOutputFile(audioFile.getAbsolutePath()); recorder.prepare(); recorder.start(); } public void stopRecording(View view){ startButton.setEnabled(true); stopButton.setEnabled(false); recorder.stop(); recorder.release(); addRecordingToMediaLibrary(); } protected void addRecordingToMediaLibrary(){ ContentValues values = new ContentValues(4); long current = System.currentTimeMillis(); values.put(MediaStore.Audio.Media.TITLE, "audio" + audioFile.getName()); values.put(MediaStore.Audio.Media.DATE_ADDED, (int)(current/1000)); values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp"); values.put(MediaStore.Audio.Media.DATA, audioFile.getAbsolutePath()); ContentResolver contentResolver = getContentResolver(); Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri newUri = contentResolver.insert(base, values); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)); Toast.makeText(this, "Added File" + newUri, Toast.LENGTH_LONG).show(); } } And here is the xml layout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="146dp" android:onClick="startRecording" android:text="Start Recording" /> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/start" android:layout_below="@+id/start" android:layout_marginTop="41dp" android:enabled="false" android:onClick="stopRecording" android:text="Stop Recording" /> </RelativeLayout> And I added permission to AndroidManifest file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.isuru.audiorecorder" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".AudioRecorderActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.RECORD_AUDIO" /> </manifest> I need to record high quality audio. Thanks!

    Read the article

  • File name after MediaStore.Images.Media.insertImage

    - by gng
    Hi! I am using MediaStore.Images.Media.insertImage(ContentResolver cr, String imagePath, String name, String description) function to insert a newly created image into gallery. System is naming the file by default, but its diferent than names of pictures taken by orginal app(Time stamp). Is there easy way to set it up?

    Read the article

  • Android read browser history

    - by Mitul Nakum
    Hello, I want to read bowser history in Android phone. I have done some document reading, then I come to know that we can read browser history by android.provider.Browser class it has final static Cursor getAllVisitedUrls(ContentResolver cr) method which returns Cursor... may i get help to handel cursor? or any example code to get Browser history. Thanks in advance

    Read the article

  • Android insertImage and the Gallery Application

    - by Steve Jones
    I am adding a bmp file to the media store using the line below ContentResolver cr = getContentResolver(); Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(cr, bmp, "name", "now")); I then go to the gallery application and it shows the image, but shows it under "Camera Pictures". Is there a way to change this to its own group, perhaps to its own group? Do I need a custom content provider for this? Thanks.

    Read the article

  • android - using resources drawable in content provider

    - by Russ Wheeler
    I am trying to pass back an image through a content provider in a separate app. I have two apps, one with the activity in (app a), the other with content provider (app b) I have app a reading an image off my SD card via app b using the following code. App a: public void but_update(View view) { ContentResolver resolver = getContentResolver(); Uri uri = Uri.parse("content://com.jash.cp_source_two.provider/note/1"); InputStream inStream = null; try { inStream = resolver.openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inStream); image = (ImageView) findViewById(R.id.imageView1); image.setImageBitmap(bitmap); } catch(FileNotFoundException e) { Toast.makeText(getBaseContext(), "error = "+e, Toast.LENGTH_LONG).show(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { Log.e("test", "could not close stream", e); } } } }; App b: @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { try { File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"pic2.png"); return ParcelFileDescriptor.open(path,ParcelFileDescriptor.MODE_READ_ONLY); } catch (FileNotFoundException e) { Log.i("r", "File not found"); throw new FileNotFoundException(); } } In app a I am able to display an image from app a's resources folder, using setImageURi and constructing a URI using the following code. int id = R.drawable.a2; Resources resources = getBaseContext().getResources(); Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(id) + '/' + resources.getResourceTypeName(id) + '/' + resources.getResourceEntryName(id) ); image = (ImageView) findViewById(R.id.imageView1); image.setImageURI(uri); However, if I try to do the same in app b (read from app b's resources folder rather than the image on the SD card) it doesn't work, saying it can't find the file, even though I am creating the path of the file from the resource, so it is definitely there. Any ideas? Does it restrict sending resources over the content provider somehow? P.S. I also got an error when I tried to create the file with File path = new File(uri); saying 'there is no applicable constructor to '(android.net.Uri)' though http://developer.android.com/reference/java/io/File.html#File(java.net.URI) Seems to think it's possible...unless java.net.URI is different to android.net.URI, in which case can I convert them? Thanks Russ

    Read the article

  • Inserting contact with android and querying the result uri returns no entries

    - by th0m4d
    Im developing an application which is dealing with the android contacts API. I implemented methods to insert, update and query contacts. So far everything worked (writing and reading contacts). At one point in my project Im experiencing a strange behaviour. I insert a contact using batch mode. I receive the URI to the RawContact. I do this in a background thread. // use batchmode for contact insertion ArrayList ops = new ArrayList(); int rawContactInsertIndex = ops.size(); // create rawContact ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI) .withValue(RawContacts.ACCOUNT_TYPE, ConstantsContract.ACCOUNT_TYPE) .withValue(RawContacts.ACCOUNT_NAME, accountName).build()); ops.add(createInsertOperation().withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) .withValue(StructuredName.DISPLAY_NAME, displayName).withValue(StructuredName.GIVEN_NAME, firstName) .withValue(StructuredName.FAMILY_NAME, lastName).build()); //other data values... ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); if (results.length 0) { result = results[0]; } Then i request and store the lookup uri RawContacts.getContactLookupUri(this.getContentResolver(), myContantRawContactUri); I am able to query the contact using the rawContactUri directly after inserting it (in the same thread). The lookup uri returns null. Uri rawContactUri = appUser.getRawContactUri(ctx); if (rawContactUri == null) { return null; } String lastPathSegment = rawContactUri.getLastPathSegment(); long rawContactId = Long.decode(lastPathSegment); if (rawContactUri != null) { contact = readContactWithID(rawContactId, ContactsContract.Data.RAW_CONTACT_ID); In a different place in the project I want to query the contact i inserted by the stored lookup uri or raw contact uri. Both return no rows from the content provider. I tried it in the main thread and in another background thread. ctx.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?", new String[] { contactID + "", ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, null); My first thought was that it could be related to the context.getContentResolver(). But the android documentation states, that the ContentResolver objects scope is the application's package, so you have on ContentResolver for the whole app. Am I right? What am I doing wrong? Why does the same rawContactUri return the contact at one place and does not on another place? And why do I get a lookup uri from a raw contact, which is not working at all?

    Read the article

  • Getting really weird long Contact Group names

    - by Pentium10
    When looking at the Contact Groups on Google Contacts or in the People application of my HTC Legend phone, I get the groups names ok eg: Friends, Family, VIP, Favorite etc... But in my application I get really wrong names such as "Family" became "System Group: Family" "Friends" became "System Group: Friends" "Favorite" became "Favorite_5656100000000_3245664334564" I use the below code to read these values: public Cursor getFromSystem() { // Get the base URI for the People table in the Contacts content // provider. Uri contacts = ContactsContract.Groups.CONTENT_URI; // Make the query. ContentResolver cr = ctx.getContentResolver(); // Form an array specifying which columns to return. String[] projection = new String[] { ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.NOTES }; Cursor managedCursor = cr.query(contacts, projection, ContactsContract.Groups.DELETED + "=0", null, ContactsContract.Groups.TITLE + " COLLATE LOCALIZED ASC"); return managedCursor; } What I am missing?

    Read the article

  • Import Contacts from .vcf file in Android 2.1

    - by Prateek Jain
    Hi All, I am able to retrieve all contacts from android in .vcf file using following code. ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); System.out.println("The value is " + cr.getType(uri)); AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); I don't know how to use this .vcf file to import all these contacts using code. The .vcf file contains all the details of all contacts including photos etc. Cheers, Prateek

    Read the article

  • Issue while access contacts of android

    - by Rishabh
    I am new for android development. I am trying read and write contacts to android addressbook. I tried following line of code for write name into android public class SecondApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentValues values = new ContentValues(); values.put(Contacts.People.NAME, "Rishabh"); ContentResolver cr = getContentResolver(); Uri uri = cr.insert(People.CONTENT_URI, values); but i am getting "The application has stopped unexpectedly. Please try again" message. what is wrong in it ? How can i access contacts of android ?

    Read the article

  • Android 2.3.3 - Messages: Wrong Status Information in the Conversation Overview

    - by Thomas Hoffmann
    On my HTC Desire Z with Android 2.3.3 I get from time to time the problem, that the status information ist wrong. That means status information says, that there is an unread, unsent or failed SMS, but this SMS is already deleted. Does anybody know, where I can reset this information? It must be stored anywhere in ContentResolver of content://mms-sms/conversations or content://sms/conversations on the thread-level, but I have no idea. Example: After I deleted a number of failed SMS in the non delivered SMS overview, the status of non delivered SMS was not reset in the Messages conversation overview though in each conversation there wasn't any undelivered SMS left.

    Read the article

  • context.getContextResolved appliaction stopped - begginner in java

    - by Szymad
    I have a problem with my app. I'm trying to execute query, but app stops every time. This error occurs while trying to execute query. I'm learing from Android Pro 3 book, but code presented in this book is deprecated. package com.example.contactsabuout; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.ContactsContract; import android.app.Activity; import android.database.Cursor; import android.util.Log; import android.content.Context; import android.view.Menu; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private static Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MainActivity.context = getApplicationContext(); Log.v("INFO", "Completed: onCreate."); } public static Context getAppContext() { return MainActivity.context; } public void doQuery(View view) { Uri peopleBaseUri = ContactsContract.Contacts.CONTENT_URI; Log.v("II","Button clicked."); Log.v("II", "Uri for ContactsContract.Contacts: " + peopleBaseUri); Context context = getAppContext(); Log.v("II", "Got context: " + context); Cursor cur; Log.v("II", "Created cursor: cur"); cur = context.getContentResolver().query(peopleBaseUri, null, null, null, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } FROM LogCat 10-28 17:45:02.513: V/INFO(4677): Completed: onCreate. 10-28 17:45:02.613: D/libEGL(4677): loaded /system/lib/egl/libGLES_android.so 10-28 17:45:02.653: D/libEGL(4677): loaded /system/lib/egl/libEGL_adreno200.so 10-28 17:45:02.723: D/libEGL(4677): loaded /system/lib/egl/libGLESv1_CM_adreno200.so 10-28 17:45:02.723: D/libEGL(4677): loaded /system/lib/egl/libGLESv2_adreno200.so 10-28 17:45:03.014: I/Adreno200-EGLSUB(4677): <ConfigWindowMatch:2078>: Format RGBA_8888. 10-28 17:45:03.054: D/OpenGLRenderer(4677): Enabling debug mode 0 10-28 17:45:03.254: D/OpenGLRenderer(4677): has fontRender patch 10-28 17:45:03.274: D/OpenGLRenderer(4677): has fontRender patch 10-28 17:45:12.873: V/II(4677): Button clicked. 10-28 17:45:12.873: V/II(4677): Uri for ContactsContract.Contacts: content://com.android.contacts/contacts, rest will be null 10-28 17:45:12.873: V/II(4677): Got context: android.app.Application@40d83d90 10-28 17:45:12.873: V/II(4677): Created cursor: cur 10-28 17:45:12.933: D/AndroidRuntime(4677): Shutting down VM 10-28 17:45:12.933: W/dalvikvm(4677): threadid=1: thread exiting with uncaught exception (group=0x40aaf228) 10-28 17:45:12.953: E/AndroidRuntime(4677): FATAL EXCEPTION: main 10-28 17:45:12.953: E/AndroidRuntime(4677): java.lang.IllegalStateException: Could not execute method of the activity 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$1.onClick(View.java:3071) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View.performClick(View.java:3538) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$PerformClick.run(View.java:14330) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Handler.handleCallback(Handler.java:608) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Handler.dispatchMessage(Handler.java:92) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Looper.loop(Looper.java:156) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.app.ActivityThread.main(ActivityThread.java:4977) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invokeNative(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invoke(Method.java:511) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 10-28 17:45:12.953: E/AndroidRuntime(4677): at dalvik.system.NativeStart.main(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): Caused by: java.lang.reflect.InvocationTargetException 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invokeNative(Native Method) 10-28 17:45:12.953: E/AndroidRuntime(4677): at java.lang.reflect.Method.invoke(Method.java:511) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.view.View$1.onClick(View.java:3066) 10-28 17:45:12.953: E/AndroidRuntime(4677): ... 11 more 10-28 17:45:12.953: E/AndroidRuntime(4677): Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.HtcContactsProvider2 uri content://com.android.contacts/contacts from pid=4677, uid=10155 requires android.permission.READ_CONTACTS 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.os.Parcel.readException(Parcel.java:1332) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:182) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:136) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.content.ContentProviderProxy.query(ContentProviderNative.java:406) 10-28 17:45:12.953: E/AndroidRuntime(4677): at android.content.ContentResolver.query(ContentResolver.java:315) 10-28 17:45:12.953: E/AndroidRuntime(4677): at com.example.contactsabuout.MainActivity.doQuery(MainActivity.java:47) 10-28 17:45:12.953: E/AndroidRuntime(4677): ... 14 more I'm trying to learn android.

    Read the article

1 2  | Next Page >