ContentProvider

2019-06-14  本文已影响0人  被罚站的树
image.png
image.png
image.png
image.png

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private String columns= ContactsContract.Contacts.DISPLAY_NAME;//希望获取姓名

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv=findViewById(R.id.tv);
        tv.setText(getQueryData());

    }

    private CharSequence getQueryData(){
        StringBuilder stringBuilder=new StringBuilder();//用于保存获取的信息
        ContentResolver resolver=getContentResolver();
        //查询记录
        Cursor cursor=resolver.query(ContactsContract.Contacts.CONTENT_URI
                ,null,null,null,null);
        //获取姓名记录的索引值
        int displayNameIndex=cursor.getColumnIndex(columns);
        for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            String displayName=cursor.getString(displayNameIndex);
            stringBuilder.append(displayName+"\n");
        }
        cursor.close();//关闭记录集
        return stringBuilder.toString();
    }

}
上一篇下一篇

猜你喜欢

热点阅读