创建了联系人类Info,和对应列表,测试时候发现ListView没有获取到值,在getInfo里向list添加项是成功的,但在onCreate输出list长度为0 ,另请教resolver.query访问电话号码的列名是什么,感谢
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList list;
int icon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
icon=R.drawable.icon;
list=new ArrayList();
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CONTACTS},1);
listView=findViewById(R.id.lv);
Toast.makeText(this,String.valueOf(list.size()),Toast.LENGTH_SHORT).show();
MyBaseAdapter adapter=new MyBaseAdapter();
listView.setAdapter(adapter);
}
class MyBaseAdapter extends BaseAdapter{
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=View.inflate(MainActivity.this,R.layout.layout,null);
TextView name=view.findViewById(R.id.name);
TextView number=view.findViewById(R.id.number);
ImageView iv=view.findViewById(R.id.image);
name.setText(list.get(position).getName());
number.setText(list.get(position).getNumber());
iv.setBackgroundResource(icon);
return view;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==1){
if (list != null) {
list.clear();
}
for(int i=0;i<permissions.length;i++){
if(grantResults[i]== PackageManager.PERMISSION_GRANTED){
getInfo();
}else{
Toast.makeText(this," "+"权限"+permissions[i]+"申请失败,不能读取联系人信息",Toast.LENGTH_SHORT).show();
}
}
}
}
public void getInfo() {
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(uri,
new String[]{"display_name"}, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String number ="";
Info info = new Info(name, number);
list.add(info);
}
cursor.close();
}
}
}