如何解决片段中的NullPointerException

时间:2014-11-17 11:26:20

标签: android

在这种情况下非常需要帮助...我有一个片段,使用sQLite加载数据库适配器...并调用一个方法,将SQLite数据库中的数据显示到我的片段布局中的listview ...

这是错误

11-17 19:22:36.659: D/jdwp(29500): sendBufferedRequest : len=0x37
11-17 19:22:36.673: W/asset(29500): AssetManager-->addDefaultAssets CIP path not exsit!
11-17 19:22:36.956: D/dalvikvm(29500): GC_FOR_ALLOC freed 40K, 9% free 2625K/2860K, paused 28ms, total 28ms
11-17 19:22:36.957: I/dalvikvm-heap(29500): Grow heap (frag case) to 4.216MB for 1536016-byte allocation
11-17 19:22:36.968: D/dalvikvm(29500): GC_FOR_ALLOC freed <1K, 6% free 4125K/4364K, paused 11ms, total 11ms
11-17 19:22:37.126: D/dalvikvm(29500): GC_FOR_ALLOC freed 1K, 6% free 4127K/4364K, paused 9ms, total 9ms
11-17 19:22:37.127: I/dalvikvm-heap(29500): Grow heap (frag case) to 14.131MB for 10394224-byte allocation
11-17 19:22:37.141: D/dalvikvm(29500): GC_FOR_ALLOC freed <1K, 2% free 14277K/14516K, paused 14ms, total 14ms
11-17 19:22:37.406: V/PhoneWindow(29500): DecorView setVisiblity: visibility = 4
11-17 19:22:37.419: V/PhoneWindow(29500): DecorView setVisiblity: visibility = 0
11-17 19:22:37.521: D/libEGL(29500): loaded /system/lib/egl/libEGL_mali.so
11-17 19:22:37.527: D/libEGL(29500): loaded /system/lib/egl/libGLESv1_CM_mali.so
11-17 19:22:37.531: D/libEGL(29500): loaded /system/lib/egl/libGLESv2_mali.so
11-17 19:22:37.565: D/OpenGLRenderer(29500): Enabling debug mode 0
11-17 19:22:37.570: V/InputMethodManager(29500): onWindowFocus: null softInputMode=288 first=true flags=#1810100
11-17 19:22:37.570: V/InputMethodManager(29500): START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{41de2868 V.E..... R.....ID 0,0-480,800} ic=null tba=android.view.inputmethod.EditorInfo@41de45c8 controlFlags=#104
11-17 19:22:37.587: V/InputMethodManager(29500): Starting input: Bind result=InputBindResult{null com.cootek.smartinputv5.oem/com.cootek.smartinput5.TouchPalIME #689}
11-17 19:22:37.742: I/InputMethodManager(29500): handleMessage: MSG_SET_ACTIVE true, was false
11-17 19:22:42.013: D/AbsListView(29500): checkAbsListViewlLogProperty get invalid command
11-17 19:22:42.070: V/PhoneWindow(29500): DecorView setVisiblity: visibility = 4
11-17 19:22:42.080: V/PhoneWindow(29500): DecorView setVisiblity: visibility = 0
11-17 19:22:42.721: V/InputMethodManager(29500): onWindowFocus: android.support.v4.widget.DrawerLayout{42964600 VFE..... .F....I. 0,0-480,690 #7f070014 app:id/drawer_layout} softInputMode=288 first=true flags=#1810100
11-17 19:22:42.722: V/InputMethodManager(29500): START INPUT: android.support.v4.widget.DrawerLayout{42964600 VFE..... .F....I. 0,0-480,690 #7f070014 app:id/drawer_layout} ic=null tba=android.view.inputmethod.EditorInfo@42aa0110 controlFlags=#105
11-17 19:22:42.764: V/InputMethodManager(29500): Starting input: Bind result=InputBindResult{com.android.internal.view.IInputMethodSession$Stub$Proxy@42aa0b00 com.cootek.smartinputv5.oem/com.cootek.smartinput5.TouchPalIME #690}
11-17 19:22:42.833: D/OpenGLRenderer(29500): Flushing caches (mode 0)
11-17 19:22:43.132: D/OpenGLRenderer(29500): Flushing caches (mode 0)
11-17 19:22:44.176: I/SurfaceTextureClient(29500): [STC::queueBuffer] (this:0x519125d0) fps:1.35, dur:1482.56, max:1346.10, min:136.46
11-17 19:22:44.219: V/Provider/Settings(29500): invalidate [system]: current 23 != cached 0
11-17 19:22:44.257: D/ActivityThread(29500): installProvider: context=android.app.ContextImpl@42948878holder=android.app.IActivityManager$ContentProviderHolder@42aa2780noisy=truenoReleaseNeeded=truestable=true
11-17 19:22:44.260: V/Provider/Settings(29500): from db cache, name = sound_effects_enabled , value = 0
11-17 19:22:45.543: I/SurfaceTextureClient(29500): [STC::queueBuffer] (this:0x519125d0) fps:13.90, dur:1367.11, max:824.16, min:9.13
11-17 19:22:45.577: D/VelocityTracker(29500): VelocityTracker: int datax = 10
11-17 19:22:45.577: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_x = 1.000000
11-17 19:22:45.577: D/VelocityTracker(29500): VelocityTracker: int datay = 10
11-17 19:22:45.577: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_y = 1.000000
11-17 19:22:45.578: D/VelocityTracker(29500): VelocityTracker: int datax = 10
11-17 19:22:45.578: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_x = 1.000000
11-17 19:22:45.578: D/VelocityTracker(29500): VelocityTracker: int datay = 10
11-17 19:22:45.578: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_y = 1.000000
11-17 19:22:45.603: D/VelocityTracker(29500): VelocityTracker: int datax = 10
11-17 19:22:45.604: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_x = 1.000000
11-17 19:22:45.604: D/VelocityTracker(29500): VelocityTracker: int datay = 10
11-17 19:22:45.604: D/VelocityTracker(29500): VelocityTracker: int m_velocity_magnify_y = 1.000000
11-17 19:22:45.696: V/Provider/Settings(29500):  from settings cache , name = sound_effects_enabled , value = 0
11-17 19:22:45.910: D/AbsListView(29500): checkAbsListViewlLogProperty get invalid command
11-17 19:22:46.007: W/DbAdapater(29500): 1
11-17 19:22:46.042: D/AndroidRuntime(29500): Shutting down VM
11-17 19:22:46.042: W/dalvikvm(29500): threadid=1: thread exiting with uncaught exception (group=0x41b2b9a8)
11-17 19:22:46.068: E/AndroidRuntime(29500): FATAL EXCEPTION: main
11-17 19:22:46.068: E/AndroidRuntime(29500): java.lang.NullPointerException
11-17 19:22:46.068: E/AndroidRuntime(29500):    at com.hanapp.gps.MyPlaces.displayListView(MyPlaces.java:100)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at com.hanapp.gps.MyPlaces.onCreateView(MyPlaces.java:59)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.Fragment.performCreateView(Fragment.java:1701)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.BackStackRecord.run(BackStackRecord.java:694)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.os.Handler.handleCallback(Handler.java:800)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.os.Handler.dispatchMessage(Handler.java:100)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.os.Looper.loop(Looper.java:194)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at android.app.ActivityThread.main(ActivityThread.java:5400)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at java.lang.reflect.Method.invokeNative(Native Method)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at java.lang.reflect.Method.invoke(Method.java:525)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:837)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
11-17 19:22:46.068: E/AndroidRuntime(29500):    at dalvik.system.NativeStart.main(Native Method)

这是我的establishment_info xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:text="TextView"
        />
    <TextView
        android:id="@+id/contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:text="TextView"
        android:layout_alignBaseline="@+id/address"
        android:layout_alignBottom="@+id/address"
        android:layout_toRightOf="@+id/address"
        />
    <TextView
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:text="TextView"
        android:layout_alignBaseline="@+id/contact"
        android:layout_alignBottom="@+id/contact"
        android:layout_toRightOf="@+id/contact"
        />




</RelativeLayout>

fragment_myplaces xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">

 <TextView android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:padding="10dp"
  android:text="Establishments in Panguil Laguna" android:textSize="20sp" />

 <EditText android:id="@+id/myFilter" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:ems="10"
  android:hint="Type here to search...">
  <requestFocus />
 </EditText>

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

</LinearLayout>

DBAdapater类。我故意拼错它。

package com.hanapp.gps;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.hanapp.gps.sqlite.DatabaseHelper;

public class DbAdapater {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_ESTAB_NAME = "estab_name";
    public static final String KEY_ESTAB_ADDRESS = "estab_address";
    public static final String KEY_ESTAB_CONTACT = "estab_contact";
    public static final String KEY_ESTAB_PHOTO = "estab_photo";
//  public static final String KEY_ESTAB_DESC = "estab_desc";
//  public static final String KEY_ESTAB_CATEGORY = "estab_category";

    private static final String TAG = "DbAdapater";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "Panguil";
    private static final String SQLITE_TABLE = "Establishments";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static final String DATABASE_CREATE =
              "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
              KEY_ROWID + " integer PRIMARY KEY autoincrement," +
              KEY_ESTAB_NAME + "," +
              KEY_ESTAB_ADDRESS + "," +
              KEY_ESTAB_CONTACT + "," +
              KEY_ESTAB_PHOTO + "," +
//            KEY_ESTAB_DESC + "," +
//            KEY_ESTAB_CATEGORY + "," +
              " UNIQUE (" + KEY_ESTAB_NAME +"));";

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context){
            super(context,DATABASE_NAME, null, DATABASE_VERSION);


        }
        @Override
          public void onCreate(SQLiteDatabase db) {
           Log.w(TAG, DATABASE_CREATE);
           db.execSQL(DATABASE_CREATE);



          }

        @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
             + newVersion + ", which will destroy all old data");
           db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
           onCreate(db);
          }


    }

         public DbAdapater(Context context) {
          this.mCtx = context;

         }


        public DbAdapater open() throws SQLException {
          mDbHelper = new DatabaseHelper(mCtx);
          mDb = mDbHelper.getWritableDatabase();
          return this;
         }

         public void close() {
          if (mDbHelper != null) {
           mDbHelper.close();
          }
         }
         //,String estab_contact, String estab_photo, String estab_desc,String estab_category
         public long createEstablishments(String estab_name, String estab_address,String estab_contact, String estab_photo){
             ContentValues initialValues = new ContentValues();
             initialValues.put(KEY_ESTAB_NAME, estab_name);
             initialValues.put(KEY_ESTAB_ADDRESS, estab_address);
             initialValues.put(KEY_ESTAB_CONTACT, estab_contact);
             initialValues.put(KEY_ESTAB_PHOTO, estab_photo);
//           initialValues.put(KEY_ESTAB_DESC, estab_desc);
//           initialValues.put(KEY_ESTAB_CATEGORY, estab_category);

             return mDb.insert(SQLITE_TABLE, null, initialValues);
         }

         public boolean deleteAllEstablishments() {

              int doneDelete = 0;
              doneDelete = mDb.delete(SQLITE_TABLE, null , null);
              Log.w(TAG, Integer.toString(doneDelete));
              return doneDelete > 0;

             }

             public Cursor fetchEstablishmentsByName(String inputText) throws SQLException {
              Log.w(TAG, inputText);
              Cursor mCursor = null;
              if (inputText == null  ||  inputText.length () == 0)  {
               mCursor = mDb.query( SQLITE_TABLE, new String[] {KEY_ROWID,
                 KEY_ESTAB_NAME, KEY_ESTAB_ADDRESS, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO,}, 
                 null, null, null, null, null);
               //, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO, KEY_ESTAB_DESC, KEY_ESTAB_CATEGORY
              }
              else {
               mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                       KEY_ESTAB_NAME, KEY_ESTAB_ADDRESS, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO,}, 
                 KEY_ESTAB_NAME + " like '%" + inputText + "%'", null,
                 null, null, null,null);
              }
              if (mCursor != null) {
               mCursor.moveToFirst();
              }
              return mCursor;
             //, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO, KEY_ESTAB_DESC, KEY_ESTAB_CATEGORY
             }

             public Cursor fetchAllEstablishments() {

              Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                      KEY_ESTAB_NAME, KEY_ESTAB_ADDRESS, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO,}, 
                null, null, null, null, null);
             //, KEY_ESTAB_CONTACT, KEY_ESTAB_PHOTO, KEY_ESTAB_DESC, KEY_ESTAB_CATEGORY
              if (mCursor != null) {
               mCursor.moveToFirst();
              }
              return mCursor;
             }

             public void insertSomeEstablishments() {


             //,"09264346557","Not Available","River Tubing/Trekking/Rafting/Camping/Hanging Bridge" +
                //          "Swimming/Biyak na Bato/Pavilion","Tourist"
             //ECO PARK
              createEstablishments("Panguil River Eco Park","Natividad Extension, Brgy. Natividad, Pangil, Luzon 4018, Philippines","09264346557","Not Available");
             }
}

MyPlaces。片段

package com.hanapp.gps;

import java.util.ArrayList;
import java.util.List;

import com.hanapp.gps.R;


import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.hanapp.gps.adapter.*;


public class MyPlaces extends Fragment {

    private DbAdapater dbHelper;
    private SimpleCursorAdapter dataAdapter;

    public MyPlaces(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

       View rootView = inflater.inflate(R.layout.fragment_myplaces, container, false);

    dbHelper = new DbAdapater(getActivity());

    dbHelper.open();


    //Clean all data

    dbHelper.deleteAllEstablishments();

    //Add some data

    dbHelper.insertSomeEstablishments();

    //Generate ListView from SQLite Database
    displayListView(rootView);
    return rootView;


      // return rootView;

    }

    public void displayListView(View v) {


          Cursor cursor = dbHelper.fetchAllEstablishments();

          // The desired columns to be bound
          String[] columns = new String[] {
            DbAdapater.KEY_ESTAB_NAME,
            DbAdapater.KEY_ESTAB_ADDRESS,
            DbAdapater.KEY_ESTAB_CONTACT,
            DbAdapater.KEY_ESTAB_PHOTO
//          DbAdapater.KEY_ESTAB_DESC,
//          DbAdapater.KEY_ESTAB_CATEGORY
            //CountriesDbAdapter.KEY_IMAGE
          };

          // the XML defined views which the data will be bound to
          int[] to = new int[] { 
            R.id.name,
            R.id.address,
            R.id.contact,
            R.id.photo
          };

          // create the adapter using the cursor pointing to the desired data 
          //as well as the layout information
          //mCurAdapter = new SimpleCursorAdapter(view.getContext(),android.R.layout.simple_list_item_1,mNotesCursor,from,to,0);

          dataAdapter = new SimpleCursorAdapter(v.getContext(), android.R.layout.simple_expandable_list_item_1, cursor, columns, to,0);


         // Assign adapter to ListView
          ListView listView = (ListView) getActivity().findViewById(R.id.listViewPlaces);
          listView.setAdapter(dataAdapter);

          listView.setOnItemClickListener(new OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> listView, View view, 
             int position, long id) {
           // Get the cursor, positioned to the corresponding row in the result set
           Cursor cursor = (Cursor) listView.getItemAtPosition(position);

           // Get the state's capital from this row in the database.
           String countryCode = 
            cursor.getString(cursor.getColumnIndexOrThrow("code"));
           Toast.makeText(getActivity().getApplicationContext(),
             countryCode, Toast.LENGTH_SHORT).show();

           }
          });

          EditText myFilter = (EditText) getActivity().findViewById(R.id.myFilter);
          myFilter.addTextChangedListener(new TextWatcher() {

           public void afterTextChanged(Editable s) {
           }

           public void beforeTextChanged(CharSequence s, int start, 
             int count, int after) {
           }

           public void onTextChanged(CharSequence s, int start, 
             int before, int count) {
            dataAdapter.getFilter().filter(s.toString());
           }
          });

          dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
                 public Cursor runQuery(CharSequence constraint) {
                     return dbHelper.fetchEstablishmentsByName(constraint.toString());
                 }
             });

         }
}

//String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
//"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
//"Linux", "OS/2" };
//ListView lv;
//lv = (ListView) rootView.findViewById(R.id.listView1);
//lv.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
//android.R.layout.simple_list_item_1 , values));
//

提前感谢您的评论和答案!

1 个答案:

答案 0 :(得分:1)

ListView listView = (ListView) getActivity().findViewById(R.id.listViewPlaces);
listView.setAdapter(dataAdapter);

您的列表视图尚未在活动层次结构中,并且无法在此处找到。在您传入的根视图上调用findViewById()作为displayListView()方法的参数:

ListView listView = (ListView)v.findViewById(R.id.listViewPlaces);