NullPointerExpection:基本联系人访问Android App

Posted

技术标签:

【中文标题】NullPointerExpection:基本联系人访问Android App【英文标题】:NullPointerExpection: Basic Contact access Android App 【发布时间】:2015-09-30 19:47:02 【问题描述】:

我按照 android 开发人员“访问联系人”的教程并逐步实施,但是当我尝试在片段中调用“setonitemclicklistener”时遇到了一个问题,该问题通过 nullpointerexpection。我尝试了多种解决方案,但无法解决问题。请帮助解决此问题。谢谢

java.lang.RuntimeException: Unable to start activity ComponentInfocom.sharpapp.findloveone/com.mycompany.myapp.addfrndactivity: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
        at android.app.ActivityThread.access$900(ActivityThread.java:170)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5635)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.mycompany.myapp.addfrndactivity$PlaceholderFragment.onActivityCreated(addfrndactivity.java:111)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1794)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:977)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
        at android.app.Activity.performStart(Activity.java:5595)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)

            

代码片段

package com.mycompany.myapp;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

import android.provider.ContactsContract;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.widget.AdapterView;
import android.widget.ListView;

public class addfrndactivity extends ActionBarActivity  

@SuppressLint("InlinedApi")
private final static String[] FROM_COLUMNS = 
        Build.VERSION.SDK_INT
                >= Build.VERSION_CODES.HONEYCOMB ?
                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
                ContactsContract.Contacts.DISPLAY_NAME
;

private final static int[] TO_IDS = 
        android.R.id.text1
;

static ListView mContactsList;

static long mContactId;

static String mContactKey;

static Uri mContactUri;

private static SimpleCursorAdapter mCursorAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addfrndactivity);
    if (savedInstanceState == null) 
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    



@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_addfrndactivity, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);


/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements
        LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener

    public PlaceholderFragment() 
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        View rootView = inflater.inflate(R.layout.fragment_addfrndactivity, container, false);
        return rootView;
    

    public void onActivityCreated(Bundle savedInstanceState) 
        super.onActivityCreated(savedInstanceState);

        getLoaderManager().initLoader(0, null, this);


        // Gets the ListView from the View list of the parent activity
        mContactsList = (ListView) getActivity().findViewById(android.R.id.list);

        // Set the item click listener to be the current fragment.
        mContactsList.setOnItemClickListener(this);

        // Gets a CursorAdapter
        mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.contacts_list_item,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
    

    @SuppressLint("InlinedApi")
    private final String[] PROJECTION =
            
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.LOOKUP_KEY,
                    Build.VERSION.SDK_INT
                            >= Build.VERSION_CODES.HONEYCOMB ?
                            ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
                            ContactsContract.Contacts.DISPLAY_NAME

            ;

    private static final int CONTACT_ID_INDEX = 0;

    private static final int LOOKUP_KEY_INDEX = 1;

    // Defines the text expression
    @SuppressLint("InlinedApi")
    private final String SELECTION =
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                    ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?" :
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?";
    // Defines a variable for the search string
    private String mSearchString;
    // Defines the array to hold values that replace the ?
    private String[] mSelectionArgs =  mSearchString ;

    @Override
    public void onItemClick(
            AdapterView<?> parent, View item, int position, long rowID) 
        // Get the Cursor
        Cursor cursor = ((SimpleCursorAdapter) parent.getAdapter()).getCursor();
        // Move to the selected contact
        cursor.moveToPosition(position);
        // Get the _ID value
        mContactId = cursor.getLong(CONTACT_ID_INDEX);
        // Get the selected LOOKUP KEY
        mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
        // Create the contact's content Uri
        mContactUri = ContactsContract.Contacts.getLookupUri(mContactId, mContactKey);

    

    @Override
    public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) 
    /*
     * Makes search string into pattern and
     * stores it in the selection array
     */
        mSelectionArgs[0] = "%" + mSearchString + "%";
        // Starts the query
        return new CursorLoader(
                getActivity(),
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                SELECTION,
                mSelectionArgs,
                null
        );
    

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
        // Put the result Cursor in the adapter for the ListView
        mCursorAdapter.swapCursor(cursor);
    

    @Override
    public void onLoaderReset(Loader<Cursor> loader) 
        // Delete the reference to the existing Cursor
        mCursorAdapter.swapCursor(null);

    



activity_addfrndactivity.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_
android:layout_
tools:context="com.mycompany.myapp.addfrndactivity"
tools:ignore="MergeRootFrame" />

fragment_addfrndactivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" 
android:layout_
android:layout_ 
tools:context="com.mycompany.myapp.addfrndactivity$PlaceholderFragment">
</RelativeLayout>

contact_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_
android:layout_/>

【问题讨论】:

【参考方案1】:

转到此布局: R.layout.fragment_addfrndactivity

并确保您有一个具有此 ID 的 ListView:android.R.id.list

很可能你没有

所以将此行更改为布局 xml 文件中的 id:

 // Gets the ListView from the View list of the parent activity
        mContactsList = (ListView) getActivity().findViewById(ID_FROM_YOUR_XML_FILE);

【讨论】:

您好,是的,我在 fragement_addfrndactivity 中没有 ListView。但我在contact_list_view.xml 中定义了ListView,如android 开发人员教程中所述。供您参考,我粘贴了所有相关的 .xml 文件

以上是关于NullPointerExpection:基本联系人访问Android App的主要内容,如果未能解决你的问题,请参考以下文章

数据库系统原理实体-联系模型

什么叫基本表?什么是视图?二者的区别和联系是什么?

Android 联系人数据库介绍以及对联系人的基本操作

什么是基本表?什么是视图?两者的区别和联系是什么?

css 联系表格7 - 更好的基本错误风格

int和Integer之间的区别和联系