SimpleCursorAdapter不工作 [英] SimpleCursorAdapter isn't working

查看:139
本文介绍了SimpleCursorAdapter不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注的谷歌开发者之一教程了解创建与应用存储添加的项目数据库,并将其retriving到ListView的,但他们使用ListActivity延长其MainActivity,我用我的BaseActivity延长MainActivity。我在路过适配器列表收到错误。也是我simpleCursorAdapter和startManagingCursor被depracted。

这是我的code:

 进口com.dusandimitrijevic.data.GroceryDbAdapter;进口android.content.Context;
进口android.content.Intent;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.support.v7.widget.Toolbar;
进口android.view.ContextMenu;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ContextMenu.ContextMenuInfo;
进口android.widget.Button;
进口android.widget.FrameLayout;
进口android.widget.ListView;
进口android.support.v4.widget.SimpleCursorAdapter;
进口android.widget.AdapterView.AdapterContextMenuInfo;公共类MainActivity扩展BaseActivity {
    私有静态最终诠释ACTIVITY_CREATE = 0;
    私有静态最终诠释ACTIVITY_EDIT = 1;    私有静态最终诠释INSERT_ID = Menu.FIRST;
    私有静态最终诠释DELETE_ID = Menu.FIRST + 1;    私人GroceryDbAdapter mDbHelper;    按钮的addItem;
    私人工具栏工具栏;
    私人的ListView ListView的;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);        的FrameLayout的FrameLayout =(的FrameLayout)findViewById(R.id.frame_container);         //膨胀的自定义活动布局
        LayoutInflater layoutInflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        查看activityView = layoutInflater.inflate(R.layout.activity_main,空,假);        frameLayout.addView(activityView);        //设置工具栏
        工具栏=(栏)findViewById(R.id.app_bar);
        setSupportActionBar(工具栏);
        getSupportActionBar()setDisplayHomeAsUpEnabled(真)。
        getSupportActionBar()setHomeButtonEnabled(真)。        mDbHelper =新GroceryDbAdapter(本);
        mDbHelper.open();
        //找到的ListView
        ListView控件=(ListView控件)findViewById(R.id.list);        fillData();        的addItem =(按钮)findViewById(R.id.button1);
        addItem.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                意向意图=新意图(MainActivity.this,AddActivity.class);
                startActivity(意向);
                overridePendingTransition(R.anim.slide_in,R.anim.slide_out);            }
        });    }    @燮pressWarnings(德precation)
    私人无效fillData(){
        光标itemsCursor = mDbHelper.fetchAllItems();
        startManagingCursor(itemsCursor);        //创建一个数组来指定,我们要在列表中显示的字段(仅TITLE)
        的String [] =由新的String [] {} GroceryDbAdapter.KEY_TITLE;        //我们希望这些字段绑定到域的阵列(在此情况下,仅有文本1)
        INT []为= INT新[] {} R.id.title;        //现在创建一个简单的游标适配器,并将其设置为显示
        SimpleCursorAdapter项目=
            新SimpleCursorAdapter(这一点,R.layout.list_item_row,itemsCursor,从,到);
        listView.setAdapter(项目);    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        super.onCreateOptionsMenu(菜单);
        menu.add(0,INSERT_ID,0,添加项目);
        返回true;
    }    公共布尔onOptionsItemSelected(INT FEATUREID,菜单项项){
        开关(item.getItemId()){
            案例INSERT_ID:
                createItem中();
                返回true;
        }        返回super.onMenuItemSelected(FEATUREID,项目);
    }    @覆盖
    公共无效onCreateContextMenu(文本菜单菜单视图V,
            ContextMenuInfo menuInfo){
        super.onCreateContextMenu(菜单,V,menuInfo);
        menu.add(0,DELETE_ID,0,删除项目);
    }    @覆盖
    公共布尔onContextItemSelected(菜单项项){
        开关(item.getItemId()){
            案例DELETE_ID:
                AdapterContextMenuInfo信息=(AdapterContextMenuInfo)item.getMenuInfo();
                mDbHelper.deleteItem(info.id);
                fillData();
                返回true;
        }
        返回super.onContextItemSelected(项目);
    }    私人无效createItem中(){
        意图I =新意图(这一点,AddActivity.class);
        startActivityForResult(ⅰ,ACTIVITY_CREATE);
    }    公共无效onListItemClick(ListView中升,视图V,INT位置,长的id){
        super.onListItemClick(L,V,位置ID);
        意图I =新意图(这一点,AddActivity.class);
        i.putExtra(GroceryDbAdapter.KEY_ROWID,身份证);
        startActivityForResult(ⅰ,ACTIVITY_EDIT);
    }    @覆盖
    保护无效的onActivityResult(INT申请code,INT结果code,意图意图){
        super.onActivityResult(要求code,结果code,意向);
        fillData();
    }
}

这是他们的code:

  / *
 *版权所有(C)2008年谷歌公司
 *
 *在Apache许可,2.0版(以下简称许可证);
 *您不能使用这个文件除了在遵守许可。
 *您可以在获得许可证的副本
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意,软件
 *许可下发布的分布在原样的基础,
 *无担保或任何形式的条件,无论是前preSS或暗示的保证。
 *请参阅许可证的特定语言的管理权限和
 *根据许可证的限制。
 * /包com.android.demo.notepad3;进口android.app.ListActivity;
进口android.content.Intent;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.view.ContextMenu;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ContextMenu.ContextMenuInfo;
进口android.widget.ListView;
进口android.widget.SimpleCursorAdapter;
进口android.widget.AdapterView.AdapterContextMenuInfo;公共类Notepadv3扩展ListActivity {
    私有静态最终诠释ACTIVITY_CREATE = 0;
    私有静态最终诠释ACTIVITY_EDIT = 1;    私有静态最终诠释INSERT_ID = Menu.FIRST;
    私有静态最终诠释DELETE_ID = Menu.FIRST + 1;    私人NotesDbAdapter mDbHelper;    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.notes_list);
        mDbHelper =新NotesDbAdapter(本);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
    }    私人无效fillData(){
        光标notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);        //创建一个数组来指定,我们要在列表中显示的字段(仅TITLE)
        的String [] =由新的String [] {} NotesDbAdapter.KEY_TITLE;        //我们希望这些字段绑定到域的阵列(在此情况下,仅有文本1)
        INT []为= INT新[] {} R.id.text1;        //现在创建一个简单的游标适配器,并将其设置为显示
        SimpleCursorAdapter指出=
            新SimpleCursorAdapter(这一点,R.layout.notes_row,notesCursor,从,到);
        setListAdapter(注);
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        super.onCreateOptionsMenu(菜单);
        menu.add(0,INSERT_ID,0,R.string.menu_insert);
        返回true;
    }    @覆盖
    公共布尔onMenuItemSelected(INT FEATUREID,菜单项项){
        开关(item.getItemId()){
            案例INSERT_ID:
                createNote();
                返回true;
        }        返回super.onMenuItemSelected(FEATUREID,项目);
    }    @覆盖
    公共无效onCreateContextMenu(文本菜单菜单视图V,
            ContextMenuInfo menuInfo){
        super.onCreateContextMenu(菜单,V,menuInfo);
        menu.add(0,DELETE_ID,0,R.string.menu_delete);
    }    @覆盖
    公共布尔onContextItemSelected(菜单项项){
        开关(item.getItemId()){
            案例DELETE_ID:
                AdapterContextMenuInfo信息=(AdapterContextMenuInfo)item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
                返回true;
        }
        返回super.onContextItemSelected(项目);
    }    私人无效createNote(){
        意图I =新意图(这一点,NoteEdit.class);
        startActivityForResult(ⅰ,ACTIVITY_CREATE);
    }    @覆盖
    保护无效onListItemClick(ListView中升,视图V,INT位置,长的id){
        super.onListItemClick(L,V,位置ID);
        意图I =新意图(这一点,NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID,身份证);
        startActivityForResult(ⅰ,ACTIVITY_EDIT);
    }    @覆盖
    保护无效的onActivityResult(INT申请code,INT结果code,意图意图){
        super.onActivityResult(要求code,结果code,意向);
        fillData();
    }
}

编辑:

AddActivity.java:

 包com.dusandimitrijevic.grocerylist;
进口com.dusandimitrijevic.data.GroceryDbAdapter;进口android.database.Cursor;
进口android.os.Bundle;
进口android.support.v7.widget.Toolbar;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;公共类AddActivity扩展BaseActivity {    私人长期mRowId;
    私人GroceryDbAdapter mDbHelper;
    私人的EditText title_edit;
    私人的EditText price_edit;
    私人按钮saveButton;    私人工具栏工具栏;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        mDbHelper =新GroceryDbAdapter(本);
        mDbHelper.open();
        的setContentView(R.layout.add_activity_layout);        工具栏=(栏)findViewById(R.id.app_bar);
        setSupportActionBar(工具栏);        //找到的EditText在add_note.xml
        title_edit =(EditText上)findViewById(R.id.titleEdit);
        price_edit =(EditText上)findViewById(R.id.priceEdit);        mRowId =(savedInstanceState == NULL)?空值 :
            (长)savedInstanceState.getSerializable(GroceryDbAdapter.KEY_ROWID);
        如果(mRowId == NULL){
            捆绑额外= getIntent()getExtras()。
            mRowId =临时演员!= NULL? extras.getLong(GroceryDbAdapter.KEY_ROWID)
                                    : 空值;
        }        populateFields();        saveButton.setOnClickListener(新View.OnClickListener(){            公共无效的onClick(查看视图){
                的setResult(RESULT_OK);
                完();
            }        });    }    私人无效populateFields(){
        如果(mRowId!= NULL){
            游标项目= mDbHelper.fetchItem(mRowId);
            startManagingCursor(项目);
            title_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_TITLE)));
            price_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_PRICE)));
        }    }    @覆盖
    保护无效的onSaveInstanceState(捆绑outState){
        super.onSaveInstanceState(outState);
        saveState和();
        outState.putSerializable(GroceryDbAdapter.KEY_ROWID,mRowId);
    }    @覆盖
    保护无效的onPause(){
        super.onPause();
        saveState和();
    }    @覆盖
    保护无效onResume(){
        super.onResume();
        populateFields();
    }    私人无效saveState和(){
        。字符串title = title_edit.getText()的toString();
        串价格= price_edit.getText()的toString()。        如果(mRowId == NULL){
            长ID = mDbHelper.createItem(标题,价格);
            如果(ID大于0){
                mRowId = ID;
            }
        }其他{
            mDbHelper.updateItem(mRowId,标题,价格);
        }
    }}

错误我收到:

这是当我的addItem点击链接,我发现了错误,但是当我上的菜单选项'添加项这是我在onCreateOption

点击申报还没有发生

  07-20 00:01:45.760:E / AndroidRuntime(27613):致命异常:主要
07-20 00:01:45.760:E / AndroidRuntime(27613):工艺:com.dusandimitrijevic.grocerylist,PID:27613
07-20 00:01:45.760:E / AndroidRuntime(27613):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.dusandimitrijevic.grocerylist / com.dusandimitrijevic.grocerylist.AddActivity}:显示java.lang.NullPointerException:尝试调用虚拟方法无效android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)对空对象引用
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread.access $ 900(ActivityThread.java:177)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1448)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.os.Handler.dispatchMessage(Handler.java:102)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.os.Looper.loop(Looper.java:145)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread.main(ActivityThread.java:5942)
07-20 00:01:45.760:E / AndroidRuntime(27613):在java.lang.reflect.Method.invoke(本机方法)
07-20 00:01:45.760:E / AndroidRuntime(27613):在java.lang.reflect.Method.invoke(Method.java:372)
07-20 00:01:45.760:E / AndroidRuntime(27613):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1400)
07-20 00:01:45.760:E / AndroidRuntime(27613):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
07-20 00:01:45.760:E / AndroidRuntime(27613):显示java.lang.NullPointerException:产生的原因试图调用虚拟方法无效android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)上空对象引用
07-20 00:01:45.760:E / AndroidRuntime(27613):在com.dusandimitrijevic.grocerylist.AddActivity.onCreate(AddActivity.java:48)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.Activity.performCreate(Activity.java:6289)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
07-20 00:01:45.760:E / AndroidRuntime(27613):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
07-20 00:01:45.760:E / AndroidRuntime(27613):10 ...更多


解决方案

你得到一个NullPointerException异常的原因是因为你调用 listView.setAdapter(项目); 之前调用的ListView =(ListView控件)findViewById(R.id.list);

只是移动调用 fillData()的初始化的ListView 电话如下:

  mDbHelper =新GroceryDbAdapter(本);
    mDbHelper.open();
    // fillData(); //这里不叫它    //找到的ListView
    ListView控件=(ListView控件)findViewById(R.id.list);    fillData(); //这里称它为

至于你的下一个NullPointerException异常,你需要初始化 saveButton 你打电话之前 saveButton.setOnClickListener()

事情是这样的:

  saveButton =(按钮)findViewById(R.id.yourButtonIdHere);saveButton.setOnClickListener(新View.OnClickListener(){            公共无效的onClick(查看视图){
                的setResult(RESULT_OK);
                完();
            }        });

I have been following one of google developers tutorials about creating an application with storing added items to database and retriving them to listView, but they are using ListActivity for extending their MainActivity and i'm using my BaseActivity to extend MainActivity. I'm getting error on passing adapter to List. Also my simpleCursorAdapter and startManagingCursor are depracted.

Here is my code:

import com.dusandimitrijevic.data.GroceryDbAdapter;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class MainActivity extends BaseActivity {
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private GroceryDbAdapter mDbHelper;

    Button addItem;
    private Toolbar toolbar;
    private ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);

         // inflate the custom activity layout
        LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);

        frameLayout.addView(activityView);

        // Setting toolbar
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mDbHelper = new GroceryDbAdapter(this);
        mDbHelper.open();


        // Locate ListView
        listView = (ListView) findViewById(R.id.list);

        fillData();

        addItem = (Button) findViewById(R.id.button1);
        addItem.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

            }
        });

    }

    @SuppressWarnings("deprecation")
    private void fillData() {
        Cursor itemsCursor = mDbHelper.fetchAllItems();
        startManagingCursor(itemsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GroceryDbAdapter.KEY_TITLE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.title};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter items = 
            new SimpleCursorAdapter(this, R.layout.list_item_row, itemsCursor, from, to);
        listView.setAdapter(items);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, "Add Item");
        return true;
    }

    public boolean onOptionsItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createItem();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, "Delete Item");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteItem(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createItem() {
        Intent i = new Intent(this, AddActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, AddActivity.class);
        i.putExtra(GroceryDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}

And this is their code:

/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.demo.notepad3;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class Notepadv3 extends ListActivity {
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private NotesDbAdapter mDbHelper;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notes_list);
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
    }

    private void fillData() {
        Cursor notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{NotesDbAdapter.KEY_TITLE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
        setListAdapter(notes);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createNote();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createNote() {
        Intent i = new Intent(this, NoteEdit.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}

EDIT:

AddActivity.java:

    package com.dusandimitrijevic.grocerylist;


import com.dusandimitrijevic.data.GroceryDbAdapter;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends BaseActivity {

    private Long mRowId;
    private GroceryDbAdapter mDbHelper;
    private EditText title_edit;
    private EditText price_edit;
    private Button saveButton;

    private Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mDbHelper = new GroceryDbAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.add_activity_layout);

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        // Locate the EditText in add_note.xml
        title_edit = (EditText) findViewById(R.id.titleEdit);
        price_edit = (EditText) findViewById(R.id.priceEdit);

        mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(GroceryDbAdapter.KEY_ROWID);
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(GroceryDbAdapter.KEY_ROWID)
                                    : null;
        }

        populateFields();

        saveButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
            }

        });

    }

    private void populateFields() {
        if (mRowId != null) {
            Cursor item = mDbHelper.fetchItem(mRowId);
            startManagingCursor(item);
            title_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_TITLE)));
            price_edit.setText(item.getString(
                    item.getColumnIndexOrThrow(GroceryDbAdapter.KEY_PRICE)));
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(GroceryDbAdapter.KEY_ROWID, mRowId);
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }

    private void saveState() {
        String title = title_edit.getText().toString();
        String price = price_edit.getText().toString();

        if (mRowId == null) {
            long id = mDbHelper.createItem(title, price);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateItem(mRowId, title, price);
        }
    }

}

ERROR I'M GETTING:

This is the error i'm getting when i click on addItem button, but nothing also happens when i click on menu option ''add item'' which i declare in onCreateOption

    07-20 00:01:45.760: E/AndroidRuntime(27613): FATAL EXCEPTION: main
07-20 00:01:45.760: E/AndroidRuntime(27613): Process: com.dusandimitrijevic.grocerylist, PID: 27613
07-20 00:01:45.760: E/AndroidRuntime(27613): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dusandimitrijevic.grocerylist/com.dusandimitrijevic.grocerylist.AddActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread.access$900(ActivityThread.java:177)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.os.Looper.loop(Looper.java:145)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread.main(ActivityThread.java:5942)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at java.lang.reflect.Method.invoke(Native Method)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at java.lang.reflect.Method.invoke(Method.java:372)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
07-20 00:01:45.760: E/AndroidRuntime(27613): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
07-20 00:01:45.760: E/AndroidRuntime(27613):    at com.dusandimitrijevic.grocerylist.AddActivity.onCreate(AddActivity.java:48)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.Activity.performCreate(Activity.java:6289)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
07-20 00:01:45.760: E/AndroidRuntime(27613):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
07-20 00:01:45.760: E/AndroidRuntime(27613):    ... 10 more

解决方案

The reason you're getting a NullPointerException is because you're calling listView.setAdapter(items); before calling listView = (ListView) findViewById(R.id.list);.

Just move the call to fillData() below the call that initializes listView:

    mDbHelper = new GroceryDbAdapter(this);
    mDbHelper.open();
    //fillData(); //don't call it here

    // Locate ListView
    listView = (ListView) findViewById(R.id.list);

    fillData(); //call it here

As for your next NullPointerException, you need to initialize saveButton before you call saveButton.setOnClickListener().

Something like this:

saveButton = (Button) findViewById(R.id.yourButtonIdHere);

saveButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
            }

        });

这篇关于SimpleCursorAdapter不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆