活动中的Nullpointer异常

时间:2011-05-05 22:42:56

标签: android listview nullpointerexception

TaskList.java

package com.teslaprime.prirt;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.LinearLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;

public class TaskList extends Activity {
  List<Task> tasks = new ArrayList<Task>();
  TaskAdapter adapter = null;
  SQLiteDatabase db = null;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent setupEntry = new Intent (TaskList.this, SetupEntry.class);
    boolean first = checkDatabase() ? true : false;

    db = openOrCreateDatabase("priRT.db",
      SQLiteDatabase.CREATE_IF_NECESSARY,null);
    db.setVersion(1);
    db.setLockingEnabled(true);
    db.execSQL("create table if not exists tasks ("
                + "id integer primary key autoincrement,"
                + "name text,"
                + "time integer,"
                + "type text);");
    db.execSQL("create table if not exists schedule ("
                + "id integer primary key autoincrement,"
                + "hours_free integer);");
    if (first) { startActivityForResult(setupEntry,0); }
    adapter = new TaskAdapter();
    Cursor cur = db.query("tasks",null,null,null,null,null,null);
    cur.moveToFirst();
    while (cur.isAfterLast() == false) {
        Task task = new Task();
        task.name = cur.getString(cur.getColumnIndex("name"));
        task.type = cur.getString(cur.getColumnIndex("type"));
        adapter.add(task);
        cur.moveToNext();
    }
    cur.close();

    Button add = (Button) findViewById(R.id.addTask);
    add.setOnClickListener(onAdd);

    ListView list = (ListView) findViewById(R.id.tasks);

    list.setAdapter(adapter);
    list.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView av, View v, int pos, long id) {
        Task task = adapter.getItem(pos);
        adapter.remove(task);
        db.execSQL("delete from tasks where name = '" + task.name + "';");
      }
    });}

    private boolean checkDatabase() {
        SQLiteDatabase checkDB = null;
          try {
            checkDB = SQLiteDatabase.openDatabase(
               "/data/data/com.teslaprime.prirt/databases/priRT.db", null,
               SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
          } catch (SQLiteException e) {}
          return checkDB == null ? true : false;
   }

  private View.OnClickListener onAdd = new View.OnClickListener() {
    public void onClick(View view) {
      Intent addTask = new Intent (view.getContext(), TaskEntry.class);
      startActivityForResult(addTask, 2);
    }
  };

  protected void onActivityResult(int req, int res, Intent data) {
    if (req == 0 && res == RESULT_OK) {
        Intent setup = new Intent (TaskList.this, Setup.class);
        startActivityForResult(setup, 1);
    }
    if (req == 2 && res == RESULT_OK) {
        Task task = new Task();
        task.name = data.getStringExtra("name");
        task.type = data.getStringExtra("type");
        adapter.add(task);
        ContentValues values = new ContentValues();
        values.put("name", data.getStringExtra("name"));
        values.put("type", data.getStringExtra("type"));
        db.insert("tasks", null, values);
    }
  }

  class TaskAdapter extends ArrayAdapter<Task> {
    TaskAdapter() {super(TaskList.this,R.layout.task,tasks);}
    private List<Task> taskList;
    private Context context;

    public View getView(int pos, View convertView, ViewGroup parent) {
      View task = convertView;
      if (convertView == null) {
        LayoutInflater inflater = getLayoutInflater();
        task = inflater.inflate(R.layout.task,null);
      }

      TextView taskName = (TextView) task.findViewById(R.id.name);
      TextView taskType = (TextView) task.findViewById(R.id.type);
      taskName.setText(tasks.get(pos).name);
      taskType.setText(tasks.get(pos).type);

      return (task);
    }
  }
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  >
  <ListView android:id="@+id/tasks"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
  />
  <Button android:id="@+id/addTask"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@id/tasks"
    android:text="Add a Task"
  />
</RelativeLayout>

错误:

I/ActivityManager(  107): Starting activity: Intent { cmp=com.teslaprime.prirt/.SetupEntry }
D/AndroidRuntime( 3246): Shutting down VM
W/dalvikvm( 3246): threadid=1: thread exiting with uncaught exception (group=0x400259f8)
E/AndroidRuntime( 3246): FATAL EXCEPTION: main
E/AndroidRuntime( 3246): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teslaprime.prirt/com.teslaprime.prirt.TaskList}: java.lang.NullPointerException
E/AndroidRuntime( 3246):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2787)
E/AndroidRuntime( 3246):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
E/AndroidRuntime( 3246):    at android.app.ActivityThread.access$2300(ActivityThread.java:135)
E/AndroidRuntime( 3246):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
E/AndroidRuntime( 3246):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3246):    at android.os.Looper.loop(Looper.java:144)
E/AndroidRuntime( 3246):    at android.app.ActivityThread.main(ActivityThread.java:4937)
E/AndroidRuntime( 3246):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3246):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 3246):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime( 3246):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime( 3246):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3246): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3246):    at com.teslaprime.prirt.TaskList.onCreate(TaskList.java:68)
E/AndroidRuntime( 3246):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
E/AndroidRuntime( 3246):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
E/AndroidRuntime( 3246):    ... 11 more

2 个答案:

答案 0 :(得分:0)

您的adapter可能已空。

如果您的tasks表为空,则不会将任何内容设置为adapter任务。

答案 1 :(得分:0)

如果此行返回null:

list.setAdapter(adapter);

这意味着您传入的适配器为null或listview为null。通过使用断点和调试模式找出它是什么。