如何继续显示选定的联系人 android

how to keep displaying the selected contacts android

所以我在 xml 文件中创建了一个列表视图,其中只有简单的 id/list 属性。

在我的 class 中,我从 ContactsContracts class.

中设置了名称和号码参数

我有 2 个问题,首先是当我单击 number/name 时,它应该突出显示并被选中并保存,除非用户取消单击它。第二个问题是我如何导入联系人照片...是否仅在字符串数组中 -> ...phone.Photo_ID?

Class:

package com.example.ankhit.saveme;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class UserContacts extends ListActivity {


    ListView lv;
    Cursor cursor1;
    String spref_identifier = "com.example.app";
    String entryIdentifierPrefix = "selectionState_listEntry_";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_contacts);

        cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
        startManagingCursor(cursor1);

        String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};

        int[] to = {android.R.id.text1,android.R.id.text2};

        SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor1,from,to);

        setListAdapter(listAdapter);

        lv = getListView();
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                saveSelectedState(position, !getSelectedState(position));
                refreshList();
            }
        });

    }


    private void saveSelectedState(int entryPosition, boolean selectedState) {
        SharedPreferences.Editor spe = this.getSharedPreferences(
                spref_identifier, Context.MODE_PRIVATE).edit();
        spe.putBoolean(entryIdentifierPrefix + entryPosition, selectedState);
        spe.commit();
    }

    private boolean getSelectedState(int entryPosition) {
        SharedPreferences sp = this.getSharedPreferences(
                spref_identifier, Context.MODE_PRIVATE);
        return sp.getBoolean(entryIdentifierPrefix + entryPosition, false); // Default value is set as false. Tweak this if necessary.
    }

    private void refreshList() {
        for (int i = 0; i < lv.getCount(); i++) {
            boolean selected = getSelectedState(i);
            ((View)lv.getItemAtPosition(i)).setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
        }
    }

    @Override
    public long getSelectedItemId() {
        return super.getSelectedItemId();
    }

    @Override
    public int getSelectedItemPosition() {
        return super.getSelectedItemPosition();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_user_contacts, 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.
        switch (item.getItemId()) {
            case R.id.homescreen:
                homescreenItem();
                return true;
            case R.id.dashboard:
                dashboardItem();
                return true;
            case R.id.about:
                aboutItem();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void homescreenItem(){
        startActivity(new Intent(UserContacts.this, Home.class));
    }

    private void dashboardItem(){
        startActivity(new Intent(UserContacts.this, Dashboard.class));
    }

    private void aboutItem(){
        new AlertDialog.Builder(this)
                .setTitle("About")
                .setMessage("Welcome to Save Me! An interactive and intuitive way to protect yourself during emergency situations and keep your location privacy. Made for a Dissertation and Developed by Ankhit Sharma")
                .setNeutralButton("OK" , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }
}

错误:

02-11 13:48:43.069    7216-7216/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ClassCastException: android.content.ContentResolver$CursorWrapperInner cannot be cast to android.view.View
            at com.example.ankhit.saveme.UserContacts.refreshList(UserContacts.java:75)
            at com.example.ankhit.saveme.UserContacts.access0(UserContacts.java:21)
            at com.example.ankhit.saveme.UserContacts.onItemClick(UserContacts.java:52)
            at android.widget.AdapterView.performItemClick(AdapterView.java:301)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1507)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3292)
            at android.widget.AbsListView.onTouchEvent(AbsListView.java:4550)
            at android.view.View.dispatchTouchEvent(View.java:7685)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2395)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2289)
            at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1575)
            at android.app.Activity.dispatchTouchEvent(Activity.java:2470)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2237)
            at android.view.View.dispatchPointerEvent(View.java:7892)
            at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3976)
            at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3860)
            at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5122)
            at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5101)
            at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5199)
            at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
            at android.os.MessageQueue.nativePollOnce(Native Method)
            at android.os.MessageQueue.next(MessageQueue.java:125)
            at android.os.Looper.loop(Looper.java:138)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.ankhit.saveme.UserContacts">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

我刚刚在做一个非常相似的任务。我使用 Android 的 SharedPreferences 解决了联系人的选择并保持他们的选择状态。

我不只是使用应用程序的 savedInstanceState,因为虽然它确实在应用程序的整个生命周期中持续存在,但当应用程序完全关闭时它不会。 SharedPreferences 可以看作是您应用程序的设置,只要您的应用程序安装在设备上,它们就会一直存在。如果您只需要在应用 运行 时保存所选联系人,并且在您的应用关闭时丢失有关已选择哪些联系人的信息也没有问题,只需 follow this tutorial.

但是,如果您改用 SharedPreferences,请执行以下操作:

写入 SharedPreferences,其中 'com.example.app' 是您在整个应用程序中用来识别一组共享首选项的随机字符串值:

private enum Contact { CONTACT1 /*,... More enums */ }
String spref_identifier = "com.example.app";
String spref_contact1_selected = "contact1_selected";
...

private void saveSelectedState(Contact contact, Boolean selectedState) {
    SharedPreferences.Editor spe = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE).edit();
    switch (contact) {
        case CONTACT1:
            spe.putBoolean(spref_contact1_selected, selectedState);
            spe.commit();
            break;
        [...]    // Other cases.
        default:
            break;
    }

}

并阅读 SharedPreferences

private Boolean getSelectedState(Contact contact) {
    SharedPreferences sp = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE);
    switch (contact) {
        case CONTACT1:
            return sp.getBoolean(spref_contact1_selected, false); // Default value is set as false. Tweak this if necessary.
        [...]    // Other cases.
        default:
            return false;
    }
}

最后,当用户点击联系人时,只需执行以下操作:

private void onButtonClick(View view) {
    Button button = (Button) view;
    // Toggle the selected state.
    saveSelectedState(Contact.CONTACT1, !getSelectedState(Contact.CONTACT1));
    boolean selected = getSelectedState(Contact.CONTACT1);
    button.setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
}

当您现在想要获取所有选定的联系人时,只需遍历枚举 Contact 中的所有项目并获取它们各自的选择状态。 另外,不要忘记在应用程序启动时检查每个选择状态,即在 onCreate 方法中。这样你的应用程序就代表了你上次使用它时的确切状态(即使它在上次使用期间崩溃了!)。

而照片请参考这个section from the Android Developers website

编辑:

把上面的方法改成这样:

String entryIdentifierPrefix = "selectionState_listEntry_";

private void saveSelectedState(int entryPosition, boolean selectedState) {
    SharedPreferences.Editor spe = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE).edit();
    spe.putBoolean(entryIdentifierPrefix + entryPosition, selectedState);
    spe.commit();
}

private boolean getSelectedState(int entryPosition) {
    SharedPreferences sp = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE);
    return sp.getBoolean(entryIdentifierPrefix + entryPosition, false); // Default value is set as false. Tweak this if necessary.
}

现在,还要加上这个方法:

private void refreshList() {
    for (int i = 0; i < lv.getCount(); i++) {
        boolean selected = getSelectedState(i);
        ((View)lv.getItemAtPosition(i)).setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
    }
}

最后,将这些行添加到您的 onCreate() 方法中:

....

lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        saveSelectedState(position, !getSelectedState(position));
        refreshList();                
    }
});

我现在无法测试此代码,但它应该可以工作。让我知道这是否可以理解。