在做读取联系人的功能时,界面自动加载时会出现java.lang.IllegalArgumentException: column 'number' does not exist异常,程序出现错误退出。
后经过查询发现在2.0以上版本时ContactsContract.Contacts.CONTENT_URI的Number属性被移动至ContactsContract.CommonDataKinds.Phone.CONTENT_URI此处。
导致目标源数据没有number列。下面给出一个经过一个小时调试修改的正确代码
LinearLayout m_LinearLayout;
ListView m_ListView; ArrayList<Map<String,String>> listData; static final String NAME="name"; static final String NUMBER="number"; public void onCreate(Bundle saveInstanceStatus){ super.onCreate(saveInstanceStatus); /*创建布局对象*/ m_LinearLayout=new LinearLayout(this); /*设置布局对象的属性*/ m_LinearLayout.setOrientation(LinearLayout.VERTICAL); m_LinearLayout.setBackgroundColor(Color.BLACK); /*创建ListView对象*/ m_ListView=new ListView(this); LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); m_ListView.setBackgroundColor(Color.WHITE); /*添加ListView到LinearLayout布局*/ m_LinearLayout.addView(m_ListView, param); /*设置显示LinearLayout布局*/ setContentView(m_LinearLayout); listData=new ArrayList<Map<String,String>>(); //获取数据库Phones的Cursor Cursor cr=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); startManagingCursor(cr); while (cr.moveToNext()) { Map<String, String> mp=new HashMap<String, String>(); long id=cr.getLong(cr.getColumnIndex("_id")); Cursor pcur=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+Long.toString(id), null, null); //处理多个号码 String phoneNumbers=""; while(pcur.moveToNext()){ String strPhoneNumber=pcur.getString(pcur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); phoneNumbers+=strPhoneNumber+":"; } phoneNumbers+="\n"; pcur.close(); String name=cr.getString(cr.getColumnIndex("display_name")); mp.put(NAME, name); mp.put(NUMBER, phoneNumbers); listData.add(mp); } ListAdapter adapter=new SimpleAdapter(this, listData, android.R.layout.simple_list_item_2, new String[] {NAME,NUMBER}, new int[] {android.R.id.text1,android.R.id.text2}); //将adapter添加到ListView中 m_ListView.setAdapter(adapter); //为ListView添加项选择事件 m_ListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub DisplayToast("滚动到第"+Long.toString(arg0.getSelectedItemId())+"项"); }@Override
public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); //为ListView添加项点击事件 m_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub DisplayToast("选中了第"+Integer.toString(arg2+1)+"项"); } }); } public void DisplayToast(String str){ Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); }