-1

我遵循Android开发人员“访问联系人”的教程并逐步实现,但我遇到了一个问题,通过nullpointerexpection,当我尝试在fragement中调用“setonitemclicklistener”。我尝试了很多解决方案,但我无法解决问题。请帮助解决这个问题。由于NullPointerExpection:基本联系人访问Android应用程序

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.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_width="match_parent" 
android:layout_height="match_parent" 
tools:context="com.mycompany.myapp.addfrndactivity" 
tools:ignore="MergeRootFrame" /> 

fragement_addfrndactivity.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" 
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_width="match_parent" 
android:layout_height="match_parent"/> 

回答

0

转到这个布局: 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); 
+0

你好,是的,我没有在fragement_addfrndactivity ListView。但我有在android开发人员教程中解释的contact_list_view.xml中定义的ListView。为了您的参考,我粘贴了所有关联的.xml文件 –