运行此代码时出现NullPointerException

时间:2013-01-03 03:55:36

标签: android nullpointerexception

因此,在此代码中,我尝试根据通过showResults()传递的查询检索游标,然后创建adapterloadermanager。我觉得问题是由我的SimpleCursorAdapter构造函数中的布局和id引起的,因为在创建布局和id时错误开始了。我使用Log和if语句来查看是否该游标是null并且没有在logcat上显示任何内容,因此必须通过游标表示没问题。

public class SearchResultsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

private ListView list;
private DatabaseTable db;
private SimpleCursorAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);
    db = new DatabaseTable(this);
    handleIntent(getIntent());
}

public void onNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        showResults(query);
    }

}

private void showResults(String query) {
    db = new DatabaseTable(this);
    Cursor cursor = db.getContactMatches(query, null);
    list = (ListView)findViewById(android.R.id.list);
    mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, 
            null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
    getLoaderManager().initLoader(0, null, this);
    list.setAdapter(mAdapter);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent contactIntent = new Intent(getApplicationContext(), ContactActivity.class);
            contactIntent.setData(getIntent().getData());
            startActivity(contactIntent);
        }
    });
}

3 个答案:

答案 0 :(得分:1)

由于您的代码在list.setAdapter(mAdapter);行上崩溃,list是唯一一个为您提供空指针的对象。

经过进一步审查,很明显您在最初宣布之后未分配list。您需要在onCreate()之后的setContentView()中添加类似的内容:

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

(如果您的对象有android:id="@android:id/list",这就是您访问它的方式;如果您分配了自己的ID,请改用R.id.your_id_here。)

答案 1 :(得分:0)

这可能是你的错误:

mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, 
            null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);

该适配器需要在Cursor输入参数的位置传递给构造函数null,如下所示:

mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, 
            cursor, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);

答案 2 :(得分:0)

在查询之前先尝试获取可读数据库:

db = new DatabaseTable(this);
Cursor cursor = db.getReadableDatabase().getContactMatches(query, null);