我正在尝试从电话簿中获取所有联系人并在ListView中显示它们。问题是联系人已经取得了联系。在ListView中成功显示,但几秒钟后,应用程序就会崩溃,获取联系人列表&在ListView中拟合项目一切都很成功但是应用程序在一段时间后崩溃了。 这是MainActivity.java -
public class MainActivity extends ListActivity {
// ArrayList<String> values = new ArrayList<String>();
String[] values;
Context mContext;
String Name;
int j=0,c=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
c=c+1;
}
phones.close();
values = new String[c];
fun();
MyArrayAdapter adapter = new MyArrayAdapter(this, values);
setListAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fun() {
// TODO Auto-generated method stub
Cursor phones1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones1.moveToNext())
{
Name=phones1.getString(phones1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones1.getString(phones1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
values[j]=Name;
j=j+1;
}
phones1.close();
}
}
和MyArrayAdapter.java是 -
public class MyArrayAdapter extends ArrayAdapter<String> {
Context context;
String[] values;
public MyArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_main, values);
// TODO Auto-generated constructor stub
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_main, parent, false);
TextView txtv = (TextView) v.findViewById(R.id.member_name);
TextView txtv1 = (TextView) v.findViewById(R.id.status);
ImageView imgv = (ImageView)v.findViewById(R.id.profile_pic);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ok);
for(int pos = 0; pos<values.length;pos++)
{
txtv.setText(values[position]);
imgv.setImageBitmap(icon);
}
return v;
}
}
请帮忙!
答案 0 :(得分:1)
您应该加载联系人并将结果传递给后台服务中的适配器,例如AsyncTask,作为在UI线程上运行长操作的IntentService将始终使您的应用程序崩溃。