Android ListView空指针异常

时间:2016-01-30 14:32:39

标签: android listview exception

我一直在努力在Android中填充ListView一段时间。有人可以帮我一把吗?

因此,我已将数据保存在2个不同表中的数据库中。一个用于设置,一个用于在listView中显示数据。但在观看了相当多的教程后,我仍然无法填充列表。我给你一些代码,我希望你们能帮助我解决这个问题。

MainActivity:

public class MainActivity extends AppCompatActivity {
//private ArrayList<String> arrayList;
public ListView viewEvents;
DataHandler dataBase;
private ListView listView;
// SQLiteDatabase data;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.ElementsView);
    dataBase = new DataHandler(this);
    showList();
}

public void showList() {

      try{
      ArrayList<ListDisplayItems> displayList = new ArrayList<ListDisplayItems>();
      //dataBase.open();
      displayList.clear();
      //String query = "SELECT * FROM " + DataHandler.DATABASE_TABLE_DISPLAY;
      Cursor c1 = DataHandler.displayQuery();
     // Cursor c1 = data.rawQuery(query, null);
      if (c1 != null && c1.getCount() != 0) {
       if (c1.moveToFirst()) {
        do {
         ListDisplayItems listDisplayItems = new ListDisplayItems();

         listDisplayItems.SetTime(c1.getString(c1
           .getColumnIndex(DataHandler.KEY_TIME_TEXT)));
         listDisplayItems.SetName(c1.getString(c1
           .getColumnIndex(DataHandler.KEY_NAME)));
         listDisplayItems.SetDays(c1.getString(c1
           .getColumnIndex(DataHandler.KEY_DAYS_OF_WEEK_TEXT)));
         displayList.add(listDisplayItems);

        } while (c1.moveToNext());
       }
      }
      c1.close();
      //dataBase.close();

      DisplayListAdapter displayListAdapter = new DisplayListAdapter(
        MainActivity.this, displayList);
      listView.setAdapter(displayListAdapter);
      }catch(Exception e){
          e.printStackTrace();
      }

     }

DisplayListAdapter类:

 DataHandler database;
 Context context;
 ArrayList<ListDisplayItems> displayList;

public DisplayListAdapter(Context context, ArrayList<ListDisplayItems> list) {
    this.context = context;
    displayList = list;
}

@Override
public int getCount() {
    return displayList.size();
}

@Override
public Object getItem(int position) {
    return displayList.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
    ListDisplayItems displayItemsList = displayList.get(position);

    if (convertView == null){
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.item_layout, null);
    }
    TextView textTime = (TextView) convertView.findViewById(R.id.itextTime);
    textTime.setText(displayItemsList.GetTime());
    TextView textName = (TextView) convertView.findViewById(R.id.itextName);
    textName.setText(displayItemsList.GetName());
    TextView textDays = (TextView) convertView.findViewById(R.id.itextDays);
    textDays.setText(displayItemsList.GetDays());


    return convertView;
}
}

ListDisplayItems类:

public class ListDisplayItems {

String iName;
String iIconRing;
String iIconAlarm;
String iTimeText;
String iDaysOfWeek;

public String GetName()
{
    return iName;
}

public void SetName(String Name)
{
    this.iName = Name;
}

public String GetIconRing()
{
    return iIconRing;
}

public void SetIconRing(String Icon)
{
    this.iIconRing = Icon;
}

public String GetIconAlarm()
{
    return iIconAlarm;
}

public void SetIconAlarm(String Icon)
{
    this.iIconAlarm = Icon;
}

public String GetTime()
{
    return iTimeText;
}

public void SetTime(String Time)
{
    this.iTimeText = Time;
}

public String GetDays()
{
    return iDaysOfWeek;
}

public void SetDays(String Days)
{
    this.iDaysOfWeek = Days;
}
}

我的DataHandler类:

public class DataHandler{
public static final String KEY_EXAMPLE = "example_of_my_keys";

static DbHelper dbhelper;
Context ctx;
static SQLiteDatabase dataBase;

public DataHandler(Context ctx){
    this.ctx = ctx;
    dbhelper = new DbHelper(ctx);
}

public static Cursor displayQuery() {
    Cursor c1 = null;
      try {

       if (dataBase.isOpen()) {
        dataBase.close();

       }
       String[] projection = {
                KEY_NAME,
                KEY_TIME_TEXT,
                KEY_DAYS_OF_WEEK_TEXT,
        };
       String sortOrder =
               KEY_ROWID + " ASC";

       dataBase = dbhelper.getWritableDatabase();
       //c1 = dataBase.rawQuery(query, null);
       c1 = dataBase.query(
                DATABASE_TABLE_DISPLAY,  // The table to query
                projection,                               // The columns to return
                null,                                // The columns for the WHERE clause
                null,                            // The values for the WHERE clause
                null,                                     // don't group the rows
                null,                                     // don't filter by row groups
                sortOrder                                 // The sort order
               );


      } catch (Exception e) {

       System.out.println("DATABASE ERROR " + e);

      }
      return c1;
}

private class DbHelper extends SQLiteOpenHelper{
           .....code creating tables and stuff///

    }
}

public DataHandler open()
{
    dataBase = dbhelper.getWritableDatabase();
    return this;
}

public void close()
{
    dbhelper.close();
}
}

我已经为listView创建了一个自定义视图布局,并设置了图标。没有错误或任何东西。我只得到一个处理过的NullPointer异常,我的列表中没有任何内容。

这是我的日志:

  

01-30 14:27:08.641:E / Trace(656):错误打开跟踪文件:没有这样的   文件或目录(2)01-30 14:27:09.419:W / dalvikvm(656):VFY:无法   找到签名中引用的类(Landroid / view / SearchEvent;)   01-30 14:27:09.419:I / dalvikvm(656):找不到方法   android.view.Window $ Callback.onSearchRequested,从方法引用   android.support.v7.view.WindowCallbackWrapper.onSearchRequested 01-30   14:27:09.429:W / dalvikvm(656):VFY:无法解析界面方法   14535:Landroid / view / Window $ Callback; .onSearchRequested   (Landroid / view / SearchEvent;)Z 01-30 14:27:09.429:D / dalvikvm(656):   VFY:在0x0002 01-30 14:27:09.439取代操作码0x72:   I / dalvikvm(656):找不到方法   android.view.Window $ Callback.onWindowStartingActionMode,引用   从方法   android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode   01-30 14:27:09.459:W / dalvikvm(656):VFY:无法解析界面   方法14539:   Landroid /视图/窗口$回调; .onWindowStartingActionMode   (Landroid /视图/ ActionMode $回调; I)Landroid /视图/ ActionMode; 01-30   14:27:09.459:D / dalvikvm(656):VFY:在0x0002处替换操作码0x72   01-30 14:27:09.989:I / dalvikvm(656):找不到方法   android.view.ViewGroup.onRtlPropertiesChanged,从方法引用   android.support.v7.widget.Toolbar.onRtlPropertiesChanged 01-30   14:27:09.989:W / dalvikvm(656):VFY:无法解析虚方法   14435:Landroid / view / ViewGroup; .onRtlPropertiesChanged(I)V 01-30   14:27:09.989:D / dalvikvm(656):VFY:在0x0007处替换操作码0x6f   01-30 14:27:10.069:I / dalvikvm(656):无法找到方法   android.content.res.TypedArray.getChangingConfigurations,引用   从方法   android.support.v7.widget.TintTypedArray.getChangingConfigurations   01-30 14:27:10.069:W / dalvikvm(656):VFY:无法解析虚拟   方法418:Landroid / content / res / TypedArray; .getChangingConfigurations   ()I 01-30 14:27:10.079:D / dalvikvm(656):VFY:替换操作码0x6e at   0x0002 01-30 14:27:10.109:I / dalvikvm(656):无法找到方法   android.content.res.TypedArray.getType,从方法引用   android.support.v7.widget.TintTypedArray.getType 01-30 14:27:10.109:   W / dalvikvm(656):VFY:无法解析虚拟方法440:   Landroid / content / res / TypedArray; .getType(I)I 01-30 14:27:10.129:   D / dalvikvm(656):VFY:在0x0002 01-30处替换操作码0x6e   14:27:10.429:I / System.out(656):DATABASE ERROR   java.lang.NullPointerException 01-30 14:27:10.429:W / System.err(656):   java.lang.NullPointerException 01-30 14:27:10.439:W / System.err(656):     在com.teosoft.mutetimer.MainActivity.showList(MainActivity.java:55)   01-30 14:27:10.439:W / System.err(656):at   com.teosoft.mutetimer.MainActivity.onCreate(MainActivity.java:27)   01-30 14:27:10.449:W / System.err(656):at   android.app.Activity.performCreate(Activity.java:5008)01-30   14:27:10.449:W / System.err(656):at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)   01-30 14:27:10.479:W / System.err(656):at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)   01-30 14:27:10.479:W / System.err(656):at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)   01-30 14:27:10.499:W / System.err(656):at   android.app.ActivityThread.access $ 600(ActivityThread.java:130)01-30   14:27:10.540:W / System.err(656):at   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1195)   01-30 14:27:10.549:W / System.err(656):at   android.os.Handler.dispatchMessage(Handler.java:99)01-30   14:27:10.559:W / System.err(656):at   android.os.Looper.loop(Looper.java:137)01-30 14:27:10.559:   W / System.err(656):at   android.app.ActivityThread.main(ActivityThread.java:4745)01-30   14:27:10.589:W / System.err(656):at   java.lang.reflect.Method.invokeNative(Native Method)01-30   14:27:10.589:W / System.err(656):at   java.lang.reflect.Method.invoke(Method.java:511)01-30 14:27:10.589:   W / System.err(656):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)   01-30 14:27:10.609:W / System.err(656):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)01-30   14:27:10.609:W / System.err(656):at   dalvik.system.NativeStart.main(Native Method)01-30 14:27:10.889:   D / dalvikvm(656):GC_CONCURRENT释放197K,3%免费11034K / 11335K,   暂停115ms + 53ms,总计392ms 01-30 14:27:11.949:   I / Choreographer(656):跳过109帧!申请可能是   在主线程上做了太多工作。 01-30 14:27:12.029:   D / gralloc_goldfish(656):未检测到GPU仿真的仿真器。

对不起,很长的帖子。我是新手。 :)

2 个答案:

答案 0 :(得分:1)

static SQLiteDatabase dataBase;  // this field is not initialized => dataBase = null

public DataHandler(Context ctx){
    this.ctx = ctx;
    dbhelper = new DbHelper(ctx);
}

public static Cursor displayQuery() {
    Cursor c1 = null;
    try {

       if (dataBase.isOpen()) {   // You try to use dataBase here and it is null
            dataBase.close();
       }
    ...

替换为

if (dataBase != null && dataBase.isOpen()) {  
    dataBase.close();
}

这应该有用。

答案 1 :(得分:0)

我认为问题出在这一行:

c1.close();

c1似乎为null,即使它为null也尝试关闭它

if (c1 != null && c1.getCount() != 0) {
    // code
}
c1.close();

如果阻止并且应用程序不应该崩溃,请将该行移到内部。但列表将是空的。