有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

游标/rawQuery上的java空指针异常

我得到了这个方法,它应该检查数据库中给定的数据,并用这些数据显示整行

movies是表的名称,year是列的名称

我已经试了几个小时,但我找不到原因,为什么它会抛出这个:

11-24 19:45:47.269: E/AndroidRuntime(18564): FATAL EXCEPTION: main
11-24 19:45:47.269: E/AndroidRuntime(18564): java.lang.IllegalStateException: Could not execute method of the activity
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.view.View$1.onClick(View.java:3633)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.view.View.performClick(View.java:4240)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.view.View$PerformClick.run(View.java:17721)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.os.Handler.handleCallback(Handler.java:730)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.os.Handler.dispatchMessage(Handler.java:92)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.os.Looper.loop(Looper.java:137)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.app.ActivityThread.main(ActivityThread.java:5103)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at java.lang.reflect.Method.invokeNative(Native Method)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at java.lang.reflect.Method.invoke(Method.java:525)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at dalvik.system.NativeStart.main(Native Method)
11-24 19:45:47.269: E/AndroidRuntime(18564): Caused by: java.lang.reflect.InvocationTargetException
11-24 19:45:47.269: E/AndroidRuntime(18564):    at java.lang.reflect.Method.invokeNative(Native Method)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at java.lang.reflect.Method.invoke(Method.java:525)
11-24 19:45:47.269: E/AndroidRuntime(18564):    at 安卓.view.View$1.onClick(View.java:3628)
11-24 19:45:47.269: E/AndroidRuntime(18564):    ... 11 more
11-24 19:45:47.269: E/AndroidRuntime(18564): Caused by: java.lang.NullPointerException
11-24 19:45:47.269: E/AndroidRuntime(18564):    at com.example.imdbproject.MainActivity.search(MainActivity.java:96)
11-24 19:45:47.269: E/AndroidRuntime(18564):    ... 14 more

package com.example.imdbproject;

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

import 安卓.os.Bundle;
import 安卓.app.Activity;
import 安卓.support.v4.widget.SimpleCursorAdapter;
import 安卓.text.TextWatcher;
import 安卓.util.Log;
import 安卓.view.Menu;
import 安卓.view.View;
import 安卓.view.View.OnClickListener;
import 安卓.widget.AdapterView;
import 安卓.widget.AdapterView.OnItemClickListener;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.ListView;
import 安卓.content.ContentValues;
import 安卓.content.Intent;
import 安卓.database.Cursor;
import 安卓.database.sqlite.SQLiteDatabase;
import 安卓.database.sqlite.SQLiteOpenHelper;

public class MainActivity extends Activity {

    ListView moviesList;
    Button searchButton;
    Button showAll;
    Button addbtn;
    Cursor cursor;
    adapter adapter_ob;
    MySQLiteHelper helper_ob;
    SQLiteDatabase db_ob;
    EditText searchET;



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

        moviesList = (ListView)findViewById(R.id.listView1);
        searchButton =(Button)findViewById(R.id.searchButton);
        addbtn = (Button)findViewById(R.id.addButton);
        showAll = (Button)findViewById(R.id.showAllButton);
        adapter_ob = new adapter(this);
        searchET = (EditText)findViewById(R.id.searchEditText);



        addbtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View arg0)
            {
                Intent addsomemoviesIntent = new Intent(MainActivity.this, AddSomeMovies.class);
                startActivity(addsomemoviesIntent);
            }
        });



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



    public void show (View arg0)
    {
        String[] from = { helper_ob.KEY_TITLE, helper_ob.KEY_YEAR };
        int[] to = { R.id.tv_title, R.id.tv_year };

        cursor = adapter_ob.queryName();

        SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to, 1);

        moviesList.setAdapter(cursorAdapter);
    }

    public void search (View arg0)
    {
        StringBuilder rtn = new StringBuilder();
        String searchx = searchET.getText().toString();


        adapter_ob.openToWrite();

        Cursor cur = db_ob.rawQuery("SELECT * FROM movies WHERE year LIKE ?", new String[] {searchx+"%"} );

        if (cur.moveToFirst()) {
            do
            {
                if(cur.getString(1).equals(searchx))
                    rtn.append("'").append(cursor.getString(1)).append("' from ").append(cursor.getString(2));
            } while (cur.moveToNext());
        }

        cursor.close();

        adapter_ob.Close();


    }





}

package com.example.imdbproject;

import 安卓.content.Context;
import 安卓.database.sqlite.SQLiteDatabase;
import 安卓.content.ContentValues;
import 安卓.database.Cursor;

public class adapter {

    SQLiteDatabase database_ob;
    MySQLiteHelper openHelper_ob;
    Context context;

    public adapter(Context c)
    {
        context = c;
    }

public adapter openToRead()
{
    openHelper_ob = new MySQLiteHelper(context,
            MySQLiteHelper.DATABASE_NAME, null, MySQLiteHelper.DATABASE_VERSION);
    database_ob = openHelper_ob.getReadableDatabase();
    return this;
}

public adapter openToWrite()
{
    openHelper_ob = new MySQLiteHelper(context,
            MySQLiteHelper.DATABASE_NAME, null, MySQLiteHelper.DATABASE_VERSION);
    database_ob = openHelper_ob.getWritableDatabase();
    return this;
}

public void Close()
{
    database_ob.close();
}

public long insertDetails(String title, String year)
{
    ContentValues cv = new ContentValues();
    cv.put(MySQLiteHelper.KEY_TITLE, title);
    cv.put(MySQLiteHelper.KEY_YEAR, year);
    openToWrite();
    long val = database_ob.insert(MySQLiteHelper.TABLE_NAME,  null,  cv);
    Close();
    return val;

}

public Cursor queryName()
{
    String[] cols = { MySQLiteHelper.KEY_ID, MySQLiteHelper.KEY_TITLE,
            MySQLiteHelper.KEY_YEAR };
    openToWrite();
    Cursor c = database_ob.query(MySQLiteHelper.TABLE_NAME,  cols,  null,  null, null, null, null);

    return c;
}



}


package com.example.imdbproject;

import java.util.LinkedList;
import java.util.List;

import 安卓.content.ContentValues;
import 安卓.content.Context;
import 安卓.database.Cursor;
import 安卓.database.sqlite.SQLiteDatabase;
import 安卓.database.sqlite.SQLiteDatabase.CursorFactory;
import 安卓.database.sqlite.SQLiteOpenHelper;
import 安卓.provider.BaseColumns;
import 安卓.util.Log;




public class MySQLiteHelper extends SQLiteOpenHelper {



public static final String DATABASE_NAME = "movie_data.db";
public static final int DATABASE_VERSION = 3;
public static final String TABLE_NAME = "movies";
public static final String KEY_ID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
public static final String SCRIPT = "Create table " + TABLE_NAME + " ("
        + KEY_ID + " integer primary key autoincrement, " + KEY_TITLE
        + " text, " + KEY_YEAR + " text);";

public MySQLiteHelper(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

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

}

@Override public void onCreate(SQLiteDatabase db) 
{
    db.execSQL(SCRIPT);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    db.execSQL("DROP TABLE " + TABLE_NAME);

    onCreate(db);
}

public long addMovie(String movietitle, String year){
    ContentValues cv = new ContentValues();
    cv.put(KEY_TITLE, movietitle);
    cv.put(KEY_YEAR, year);

    SQLiteDatabase sd = getWritableDatabase();

    long result = sd.insert(TABLE_NAME,  KEY_TITLE,  cv);
    return result;

}

}


共 (1) 个答案

  1. # 1 楼答案

    正如MarsAtomic所指出的,您的db_ob在整个代码中没有引用您的数据库,这就是导致空指针异常的原因。您似乎正在使用database_ob在适配器类中引用数据库

    也许您可以尝试在适配器类中创建一个方法,以返回搜索函数的游标:

    public Cursor querySearch(string sql, string[] selectionArgs)
    {
        Cursor c = database_ob.rawQuery(sql, selectionArgs);
        return c;
    }
    

    将搜索函数中的第96行替换为

        Cursor cur = adapter_ob.querySearch("SELECT * FROM movies WHERE year LIKE ?", new String[] {searchx+"%"} );
    

    我希望这对你的npe有帮助