我上过这堂课:
public class DisplayItems extends ListActivity{
ArrayList<String> contactNames = new ArrayList<>();
ArrayList<String> contactNumbers = new ArrayList<>();
//Get the contacts in the phone
public void getContacts(){
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumbers.add(phoneNumber);
contactNames.add(name + "\n" + phoneNumber);
}
phones.close();
}
//displaying contacts name and numbers in a listView
public void displayContacts(){
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<>(this,
android.R.layout.simple_list_item_checked, contactNames));
}
}
现在我想在这一个中使用该类:
public class PickNumbersActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_numbers);
//Get message text
Intent i = getIntent();
Bundle extras = i.getExtras();
String message_text = extras.getString("message");
DisplayItems display = new DisplayItems();
display.getContacts();
display.displayContacts();
}
}
但它不起作用......而且我是android studio的新手,当我的应用程序无法运行时,我甚至不知道在哪里查找错误消息 感谢。
答案 0 :(得分:0)
首先,您正在尝试实例化DisplayItems
扩展ListActivity
的{{1}}类,您不应该像这样使用它。一个更好的方法是将DisplayItems
变成DisplayItemsFragment
,就像这样。
首先请确保您的ID为container
。
然后将其添加到您的PickNumbersActivity
:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DisplayItemsFragment())
.commit();
}
最后让你的类像这样扩展ListFragment:
public class DisplayItemsFragment extends ListFragment{
@Override
public void onCreate(Bundle savedInstanceState) {
getContacts();
}
//Get the contacts in the phone
public void getContacts(){
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumbers.add(phoneNumber);
contactNames.add(name + "\n" + phoneNumber);
}
phones.close();
displayContacts();
}
//displaying contacts name and numbers in a listView
public void displayContacts(){
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<>(this,
android.R.layout.simple_list_item_checked, contactNames));
}
}
如果您有更多问题,请查看官方working with fragments documentation。