onItemClick()中的NullPointerException

时间:2015-04-13 18:30:28

标签: java android onitemclick

我正在创建导航抽屉列表视图,根据列表视图的位置在特定文本视图中进行更改,但总是多次出现该异常并且我不知道如何解决它

MainActivity Class

public class DBHelper extends SQLiteOpenHelper {

     private static String DB_NAME = "duaa.sqlite";
     private SQLiteDatabase db;
     private final Context context;
     private String DB_PATH;

     public DBHelper(Context context) {
      super(context, DB_NAME, null, 1);
      this.context = context;
      DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
     }

     public void createDataBase() throws IOException {

      boolean dbExist = checkDataBase();
      if (dbExist) {

      } else {
       this.getReadableDatabase();
       try {
        copyDataBase();
       } catch (IOException e) {
        throw new Error("Error copying database");
       }
      }
     }

     private boolean checkDataBase() {
      File dbFile = new File(DB_PATH + DB_NAME);
      return dbFile.exists();
     }

     private void copyDataBase() throws IOException {

      InputStream myInput = context.getAssets().open(DB_NAME);
      String outFileName = DB_PATH + DB_NAME;
      OutputStream myOutput = new FileOutputStream(outFileName);
      byte[] buffer = new byte[1024];
      int length;
      while ((length = myInput.read(buffer)) > 0) {
       myOutput.write(buffer, 0, length);
      }

      // Close the streams
      myOutput.flush();
      myOutput.close();
      myInput.close();

     }

     public Cursor getData() {
      String myPath = DB_PATH + DB_NAME;
      db = SQLiteDatabase.openDatabase(myPath, null,
        SQLiteDatabase.OPEN_READONLY);
      Cursor c = db.query("main", null, null, null, null,null,null);
       // Note: Master is the one table in External db. Here we trying to access the records of table from external db.
      return c;
     }

     @Override
     public void onCreate(SQLiteDatabase arg0) {
      // TODO Auto-generated method stub
     }

     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // TODO Auto-generated method stub
     }
}

扩展SQLiteOpenHelper的DbHelper类

public class MainActivity extends ActionBarActivity {

        ListView lv;
        DrawerList adapter;
        DrawerLayout drawer;
        String[] duaaList;
        ActionBarDrawerToggle drawerToggle;
        TextView tv;
        ArrayList<String>data;
        DBHelper helper;




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

            duaaList = getResources().getStringArray(R.array.duaa);

            drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

            tv = (TextView) findViewById(R.id.tvDesc);

            lv = (ListView) findViewById(R.id.left_drawer);

            adapter = new DrawerList();

            lv.setAdapter(adapter);



            drawerToggle = new  ActionBarDrawerToggle(this,drawer,0,0);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    selectItem(position);

                    changeText(position);


                }
                public void selectItem(int position){
                    lv.setItemChecked(position, true);
                    setTitle(duaaList[position]);
                }
                public void setTitle(String title){
                    getSupportActionBar().setTitle(title);
                }

              //set data into a textview according to the position of the list 
                public void changeText(int position){
                try{    

                    lv.setItemChecked(position, true);
                    lv.setSelection(position);
                    drawer.closeDrawer(lv);

                    tv.setText(data.get(position));       
                }catch(Exception e){
                    e.printStackTrace();
                }
             }

            });

    }





        public void changeTextView(){
            helper = new DBHelper(getBaseContext());
            try {
                helper.createDataBase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Cursor c = helper.getData();
          if(c.moveToFirst() && c != null)
          {
            do {
                data.add(c.getString(c.getColumnIndex("desc")));
            } while (c.moveToNext());   
          } 
        }



        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            int id = item.getItemId();

            if (id == R.id.action_settings) {
                finish();
            }

            return super.onOptionsItemSelected(item);
        }

        class DrawerList extends BaseAdapter{


            @Override
            public int getCount() {
                return duaaList.length;
            }

            @Override
            public Object getItem(int position) {
                return duaaList[position];
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null){
                    v = getLayoutInflater().inflate(R.layout.duaa_list_item , parent , false);
                }
                TextView tv = (TextView) v.findViewById(R.id.tv2);
                tv.setText(duaaList[position]);

                return v;
            }
        }

    }

这里是xml文件

 <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- The main content view -->

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="480dp" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Medium Text"
                    android:id="@+id/tvDesc"
                    android:layout_gravity="center"
                    android:paddingTop="10dp"
                    />
            </LinearLayout>

    </ScrollView>
        </FrameLayout>
        <!-- The navigation drawer -->
        <ListView android:id="@+id/left_drawer"
            android:layout_width="290dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:splitMotionEvents="true"
            android:soundEffectsEnabled="true"
            android:divider="@android:color/darker_gray"
            android:dividerHeight="1dp"
            android:background="#ffbababa"/>

    </android.support.v4.widget.DrawerLayout>

以下是例外:

  

04-13 14:26:00.573:W / System.err(18010):   java.lang.NullPointerException 04-13 14:26:00.573:   W / System.err(18010):at   com.anabil.duaaapp.MainActivity $ 1.changeText(MainActivity.java:98)   04-13 14:26:00.573:W / System.err(18010):at   com.anabil.duaaapp.MainActivity $ 1.onItemClick(MainActivity.java:78)   04-13 14:26:00.573:W / System.err(18010):at   android.widget.AdapterView.performItemClick(AdapterView.java:299)   04-13 14:26:00.573:W / System.err(18010):at   android.widget.AbsListView.performItemClick(AbsListView.java:1113)   04-13 14:26:00.573:W / System.err(18010):at   android.widget.AbsListView $ PerformClick.run(AbsListView.java:2911)   04-13 14:26:00.573:W / System.err(18010):at   android.widget.AbsListView $ 3.run(AbsListView.java:3645)04-13   14:26:00.573:W / System.err(18010):at   android.os.Handler.handleCallback(Handler.java:733)04-13   14:26:00.573:W / System.err(18010):at   android.os.Handler.dispatchMessage(Handler.java:95)04-13   14:26:00.573:W / System.err(18010):at   android.os.Looper.loop(Looper.java:136)04-13 14:26:00.573:   W / System.err(18010):at   android.app.ActivityThread.main(ActivityThread.java:5001)04-13   14:26:00.573:W / System.err(18010):at   java.lang.reflect.Method.invokeNative(Native Method)04-13   14:26:00.573:W / System.err(18010):at   java.lang.reflect.Method.invoke(Method.java:515)04-13 14:26:00.573:   W / System.err(18010):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:785)   04-13 14:26:00.573:W / System.err(18010):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)04-13   14:26:00.573:W / System.err(18010):at   dalvik.system.NativeStart.main(原生方法)

1 个答案:

答案 0 :(得分:0)

我看不到您初始化ArrayList<String> data的位置,我只看到您尝试在importDB()中添加一些内容。我怀疑你能够看到这个日志:Log.d("TAG" , "the database has been successfully readed :)" );。导致NullPointerException的行很可能就是这一行:tv.setText(data.get(position));

无论如何,几个笔记:

  1. 在您粘贴的代码中,您尝试在UI线程中处理数据库导入(因为您直接从readOrCopyFile()调用onCreate())。这是一个非常糟糕的主意,因为您的应用程序可能会在很长一段时间内无法响应。至少将其提取到AsyncTask
  2. 日志显示您的NullPointerException发生在changeText()。假设您已经在某处初始化了data数组,为了避免出现进一步的问题,您应该在调用size()之前完全检查它data.get(position)