0

我无法从我的数据库中显示一个事件信息。在 DayPlan.java 中的事件列表中单击我的事件后,它应该向我显示有关此事件的一些信息,但它只会使整个应用程序崩溃并出现错误:Nullpointer exception :( 我使用了 thiscodeasa base: Database example

错误出现在 ViewEvent 的 OnPostExecute 中,有人可以帮我吗?

我的数据库连接器:

    package com.examples.android.calendar;


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


public class DatabaseConnector {

    private static final String DB_NAME = "watchaday";
    private SQLiteDatabase database;
    private DatabaseOpenHelper dbOpenHelper;

    public DatabaseConnector(Context context) {
        dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
    }

       public void open() throws SQLException 
       {
          //open database in reading/writing mode
          database = dbOpenHelper.getWritableDatabase();
       } 

       public void close() 
       {
          if (database != null)
             database.close();
       }       

       public void insertContact(String date, String hour_from, String hour_to, String event, String colour) 
               {
                  ContentValues newCon = new ContentValues();
                  newCon.put("date", date);
                  newCon.put("hour_from", hour_from);
                  newCon.put("hour_to", hour_to);
                  newCon.put("event", event);
                  newCon.put("colour", colour);


                  open();
                  database.insert("calendar_events", null, newCon);
                  close();
               }


               public void updateContact(long id, String date, String hour_from, String hour_to, String event, String colour) 
               {
                  ContentValues editCon = new ContentValues();
;
                  editCon.put("date", date);
                  editCon.put("hour_from", hour_from);
                  editCon.put("hour_to", hour_to);
                  editCon.put("event", event);
                  editCon.put("colour", colour);

                  open();
                  database.update("calendar_events", editCon, "_id=" + id, null);
                  close();
               }


               public Cursor getAllContacts() 
               {
                  return database.query("calendar_events", new String[] {"_id", "event"}, 
                     null, null, null, null, "date");
               }

               public Cursor getOneContact(long id) 
               {
                  return database.query("calendar_events", null, "_id=" + id, null, null, null, null);
               }

               public void deleteContact(long id) 
               {
                  open(); 
                  database.delete("calendar_events", "_id=" + id, null);
                  close();
               }
}

我的数据库助手:

 package com.examples.android.calendar;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createQuery = "CREATE TABLE calendar_events (_id integer primary key autoincrement,date, hour_from, hour_to, event, colour);";                 
        db.execSQL(createQuery);        
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

我的事件列表代码:

 package com.examples.android.calendar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class DayPlan extends ListActivity {

     public static final String ROW_ID = "row_id";
     private ListView conListView;
     private CursorAdapter conAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        conListView=getListView();
        conListView.setOnItemClickListener(viewConListener);

        // map each name to a TextView
        String[] from = new String[] { "event" };
        int[] to = new int[] { R.id.countryTextView };
        conAdapter = new SimpleCursorAdapter(DayPlan.this, R.layout.day_plan, null, from, to);
        setListAdapter(conAdapter); // set adapter
    }


    @Override
    protected void onResume() 
    {
       super.onResume();  
       new GetContacts().execute((Object[]) null);
     } 


    @Override
    protected void onStop() 
    {
       Cursor cursor = conAdapter.getCursor();

       if (cursor != null) 
          cursor.deactivate();

       conAdapter.changeCursor(null);
       super.onStop();
    }    


    private class GetContacts extends AsyncTask<Object, Object, Cursor> 
    {
       DatabaseConnector dbConnector = new DatabaseConnector(DayPlan.this);

       @Override
       protected Cursor doInBackground(Object... params)
       {
          dbConnector.open();
          return dbConnector.getAllContacts(); 
       } 

       @Override
       protected void onPostExecute(Cursor result)
       {
          conAdapter.changeCursor(result); // set the adapter's Cursor
          dbConnector.close();
       } 
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
       super.onCreateOptionsMenu(menu);
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.dayplan_menu, menu);
       return true;
    }   

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
       Intent addContact = new Intent(DayPlan.this, AddEvent.class);
       startActivity(addContact);
       return super.onOptionsItemSelected(item);
    }

    OnItemClickListener viewConListener = new OnItemClickListener() 
    {
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
       {         
          Intent viewCon = new Intent(DayPlan.this, ViewEvent.class);
          viewCon.putExtra(ROW_ID, arg3);
          startActivity(viewCon);
       }
    };    

}

我的查看事件代码在 OnPostExecute 部分中使应用程序崩溃:

视图事件.java:

public class ViewEvent extends Activity {

   private long rowID;
   private TextView dateTv;
   private TextView hourfromTv;
   private TextView hourtoTv; 
   private TextView eventTv;
   private TextView colourTv; 

   @Override
   public void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.view_event);

      setUpViews();
      Bundle extras = getIntent().getExtras();
      rowID = extras.getLong(DayPlan.ROW_ID); 
   }

   private void setUpViews() {
       dateTv = (TextView) findViewById(R.id.date);
       hourfromTv = (TextView) findViewById(R.id.hour_fromText);
       hourtoTv = (TextView) findViewById(R.id.hour_toText);
       eventTv = (TextView) findViewById(R.id.eventText);
       colourTv = (TextView) findViewById(R.id.colourText);

   }

   @Override
   protected void onResume()
   {
      super.onResume();
      new LoadContacts().execute(rowID);
   } 

   private class LoadContacts extends AsyncTask<Long, Object, Cursor> 
   {
      DatabaseConnector dbConnector = new DatabaseConnector(ViewEvent.this);

      @Override
      protected Cursor doInBackground(Long... params)
      {
         dbConnector.open();
         return dbConnector.getOneContact(params[0]);
      } 

      @Override
      protected void onPostExecute(Cursor result)
      {

         super.onPostExecute(result);

         result.moveToFirst();
         // get the column index for each data item
       int dateindex = result.getColumnIndex("date");
         int hourfromIndex = result.getColumnIndex("hour_from");
         int hourtoIndex = result.getColumnIndex("hour_to");
         int eventIndex = result.getColumnIndex("event");
         int colourIndex = result.getColumnIndex("colour");

         dateTv.setText(result.getString(dateindex));
         hourfromTv.setText(result.getString(hourfromIndex));
         hourtoTv.setText(result.getString(hourtoIndex));
         eventTv.setText(result.getString(eventIndex));
         colourTv.setText(result.getString(colourIndex));

         result.close();
         dbConnector.close();
      }
   } 


   @Override
   public boolean onCreateOptionsMenu(Menu menu) 
   {
      super.onCreateOptionsMenu(menu);
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.view_event_menu, menu);
      return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) 
   {
      switch (item.getItemId())
      {
         case R.id.editItem:
            Intent addEditContact =
               new Intent(this, AddEvent.class);

            addEditContact.putExtra(DayPlan.ROW_ID, rowID);

            startActivity(addEditContact); 
            return true;

         case R.id.deleteItem:
            deleteContact();
            return true;

         default:
            return super.onOptionsItemSelected(item);
      } 
   }

   private void deleteContact()
   {

      AlertDialog.Builder alert = new AlertDialog.Builder(ViewEvent.this);

      alert.setTitle(R.string.confirmTitle); 
      alert.setMessage(R.string.confirmMessage); 

      alert.setPositiveButton(R.string.delete_btn,
         new DialogInterface.OnClickListener()
         {
            public void onClick(DialogInterface dialog, int button)
            {
               final DatabaseConnector dbConnector = 
                  new DatabaseConnector(ViewEvent.this);

               AsyncTask<Long, Object, Object> deleteTask =
                  new AsyncTask<Long, Object, Object>()
                  {
                     @Override
                     protected Object doInBackground(Long... params)
                     {
                        dbConnector.deleteContact(params[0]); 
                        return null;
                     } 

                     @Override
                     protected void onPostExecute(Object result)
                     {
                        finish(); 
                     }
                  };

               deleteTask.execute(new Long[] { rowID });               
            }
         }
      );

      alert.setNegativeButton(R.string.cancel_btn, null).show();
   }
}

错误 :

12-30 17:52:29.334:E/AndroidRuntime(1173):致命异常:主要

12-30 17:52:29.334: E/AndroidRuntime(1173): java.lang.NullPointerException

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 com.examples.android.calendar.ViewEvent$LoadContacts.onPostExecute(ViewEvent.java:76)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 com.examples.android.calendar.ViewEvent$LoadContacts.onPostExecute(ViewEvent.java:1)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.os.AsyncTask.finish(AsyncTask.java:631)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.os.AsyncTask.access$600(AsyncTask.java:177)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.os.Handler.dispatchMessage(Handler.java:99)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.os.Looper.loop(Looper.java:137)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 android.app.ActivityThread.main(ActivityThread.java:4745)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 java.lang.reflect.Method.invokeNative(Native Method)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 java.lang.reflect.Method.invoke(Method.java:511)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

12-30 17:52:29.334: E/AndroidRuntime(1173): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

12-30 17:52:29.334: E/AndroidRuntime(1173): at dalvik.system.NativeStart.main(Native Method) 12-30 17:52:31.463: I/Process(1173): 发送信号。PID:1173 SIG:9 12-30 17:52:32.305:E/Trace(1191):打开跟踪文件时出错:没有这样的文件或目录 (2)

4

1 回答 1

0

这里的错误是由于错误的资源 Id.Still 阅读下面

如果查询中至少返回一条记录,result.moveToFirst() 将返回 true。
正确的使用方法:

if(result.moveToFirst()){

       int dateindex = result.getColumnIndex("date");
         int hourfromIndex = result.getColumnIndex("hour_from");
         int hourtoIndex = result.getColumnIndex("hour_to");
         int eventIndex = result.getColumnIndex("event");
         int colourIndex = result.getColumnIndex("colour");

         dateTv.setText(result.getString(dateindex));
         hourfromTv.setText(result.getString(hourfromIndex));
         hourtoTv.setText(result.getString(hourtoIndex));
         eventTv.setText(result.getString(eventIndex));
         colourTv.setText(result.getString(colourIndex));

}
于 2012-12-30T17:54:33.770 回答