简体   繁体   English

访问数据库SQLiteopenHelper方法时,应用程序崩溃(nullpointerexception)

[英]Application crash (nullpointerexception) when accessing to database SQLiteopenHelper methods

I've got another problem with SQLite database. 我有SQLite数据库的另一个问题。 I am accessing to database with help of this class, and also, here I create database and pre-fill it.: 我将在此类的帮助下访问数据库,并且在这里我创建数据库并预填充它。

public class DatabaseHandler extends SQLiteOpenHelper {


    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "mydatabase";

    // Table names
    private static final String TABLE_DEVICE = "device";
    private static final String TABLE_ICON = "icon";

    // Column names of device table
    private static final String ID_DEVICE = "idDevice";
    private static final String UNIT_NUMBER = "unitNumber";
    private static final String DEVICE_ID = "deviceId";
    private static final String FK_ICON = "kdIcon";

    // Column names of icon table
    private static final String ID_ICON = "idIcon";
    private static final String CATEGORY = "category";
    private static final String ON = "iconOn";
    private static final String OFF = "iconOff";
    private static final String ON_COOLING = "onCooling";
    private static final String ON_HEATING = "onHeating";
    private static final String ICON_0 = "icon0";
    private static final String ICON_10 = "icon10";
    private static final String ICON_20 = "icon20";
    private static final String ICON_25 = "icon25";
    private static final String ICON_30 = "icon30";
    private static final String ICON_40 = "icon40";
    private static final String ICON_50 = "icon50";
    private static final String ICON_60 = "icon60";
    private static final String ICON_75 = "icon75";
    private static final String ICON_80 = "icon80";
    private static final String ICON_90 = "icon90";
    private static final String ICON_100 = "icon100";

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


    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createDeviceTable = "CREATE  TABLE " + TABLE_DEVICE + " ("
                + ID_DEVICE + " INTEGER PRIMARY KEY NOT NULL  UNIQUE , "
                + UNIT_NUMBER + " INTEGER NOT NULL  UNIQUE , " + DEVICE_ID
                + " INTEGER NOT NULL  UNIQUE , " + FK_ICON + " INTEGER)";

        String createIconTable = "CREATE  TABLE " + TABLE_ICON + " (" + ID_ICON
                + " INTEGER PRIMARY KEY NOT NULL  UNIQUE , " + CATEGORY
                + " INTEGER NOT NULL , " + ON + " TEXT, " + OFF + " TEXT, "
                + ON_COOLING + " TEXT, " + ON_HEATING + " TEXT, " + ICON_0
                + " TEXT, " + ICON_10 + " TEXT, " + ICON_20 + " TEXT, "
                + ICON_25 + " TEXT, " + ICON_30 + " TEXT, " + ICON_40
                + " TEXT, " + ICON_50 + " TEXT, " + ICON_60 + " TEXT, "
                + ICON_75 + " TEXT, " + ICON_80 + " TEXT, " + ICON_90
                + " TEXT, " + ICON_100 + " TEXT)";

        db.execSQL(createDeviceTable);
        db.execSQL(createIconTable);

        ContentValues values = new ContentValues();
        values.put(ID_ICON, 1);
        values.put(CATEGORY, 3);
        values.put(ON, "lightbulb_0_v2");
        values.put(OFF, "lightbulb_100_v2");
        db.insert(TABLE_ICON, null, values);
        values.clear();

        values.put(ID_ICON, 2);
        values.put(CATEGORY, 3);
        values.put(ON, "lightbulb_0_v1");
        values.put(OFF, "lightbulb_max_v1");
        db.insert(TABLE_ICON, null, values);
        values.clear();

        values.put(ID_ICON, 3);
        values.put(CATEGORY, 3);
        values.put(ON, "electric_outlet_on");
        values.put(OFF, "electric_outlet_off");
        db.insert(TABLE_ICON, null, values);
        values.clear();

        values.put(ID_DEVICE, 1);
        values.put(UNIT_NUMBER, 35100191);
        values.put(DEVICE_ID, 116);
        values.put(FK_ICON, 2);
        db.insert(TABLE_DEVICE, null, values);
        values.clear();

    }

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

        // Create tables again
        onCreate(db);

    }

    // It is used to show all availabe icons of category.
    public List<String> getAllIconsOfOldCategory(int oldCategory) {
        List<String> iconsList = new ArrayList<String>();

        String SqlSelectIconsQuery = "";
        // if (oldCategory == 3)
        SqlSelectIconsQuery = "SELECT " + ON + " FROM " + TABLE_ICON;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(SqlSelectIconsQuery, null);
        if (cursor.moveToFirst()) {
            do {
                iconsList.add(cursor.getString(0));
                Log.v("BAZA", cursor.getString(0));
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return iconsList;
        // return null;
    }

    public String getIcon(int deviceId, int unite_number, int status, int oldCategory) {
         SQLiteDatabase db = this.getReadableDatabase();
        // if (oldCategory == 3)
        String SqlFindIconId = "SELECT " + FK_ICON + " FROM " + TABLE_DEVICE
                + " WHERE " + UNIT_NUMBER + " = " + unite_number + " AND "
                + DEVICE_ID + " = " + deviceId;

        Cursor cursor = db.rawQuery(SqlFindIconId, null);
        if(cursor !=null){
            String icon;
            if(status == 0){
                icon = "SELECT "+ON+" FROM "+TABLE_ICON+ " WHERE "+ID_ICON +" = "+ cursor.getString(0);
            }else{
                icon = "SELECT "+OFF+" FROM "+TABLE_ICON+ " WHERE "+ID_ICON +" = "+ cursor.getString(0);
            }
            db.close();
            return db.rawQuery(SqlFindIconId, null).getString(0);
        }
        db.close();
        return null;
    }

}

Now, you can see the there are two methods. 现在,您可以看到有两种方法。 First, getAllIconsOfOldCategory(int oldCategory) and second getIcon(int deviceId, int unite_number, int status, int oldCategory) . 首先, getAllIconsOfOldCategory(int oldCategory)和第二个getIcon(int deviceId, int unite_number, int status, int oldCategory) In application, where I am using first metod, everything works....but when I try to use second method, application throws NullPointerException before getIcon() method start executing and application is Forced closed. 在我使用第一个方法的应用程序中,一切正常....但是当我尝试使用第二个方法时,应用程序在getIcon()方法开始执行并强制关闭应用程序之前抛出NullPointerException。

So, below I will provide the class, where I use this Databashandler class and its methods. 因此,在下面,我将提供使用该Databashandler类及其方法的类。 Here is, lets call it classA.java. 在这里,将其称为classA.java。 So, classA (this extends to another class)is used to render listView and every individual line of listView. 因此,classA(扩展到另一个类)用于呈现listView和listView的每一行。 ([ImageView][Text][SwitchButton]-->this is one line in listView). ([ImageView] [Text] [SwitchButton]->这是listView中的一行)。 Here I've got onCreate() method: I think it's nothing wrong with this method, because it doesn't show any error and it works when I press on imageView(you will see more explanation below). 在这里,我有onCreate()方法:我认为该方法没有问题,因为它没有显示任何错误,并且在按imageView时可以正常工作(您将在下面看到更多说明)。

private DatabaseHandler db;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    db = new DatabaseHandler(classA.this
            .getParent());

}

So, in this class, there is methos renderDevice() which is used to render all lines in listview, and it return view. 因此,在此类中,有方法renderDevice()用来呈现listview中的所有行,并返回view。 And my goal is, to check, if there is image in database, show this one, and if there is not, than show pre defined one. 我的目标是检查数据库中是否有图像,然后显示该图像,如果没有,则显示预定义的图像。 But, it doesn't work... It's all right till the line, where I call db.getIcon() method. 但是,它行不通...直到行,我调用db.getIcon()方法db.getIcon() Then it show the error. 然后显示错误。 And the method don't even start executing. 而且该方法甚至没有开始执行。

ImageView device_status_image = (ImageView) lightView
                .findViewById(R.id.device_status_image);
        Settings settings = Settings.getInstance();  
        String icon = db.getIcon(light.id, settings.getLastPkAccessPoint(), status, light.oldCategory);

        if ( icon != null) {
            int resId = getResources().getIdentifier(icon, "drawable",
                    getPackageName());
            device_status_image.setImageResource(resId);
        } else
            device_status_image.setImageResource(R.drawable.normal_icon); 

        }

But, moreover, I've got onClickListener on device_status_image . 但是,另外,我有onClickListenerdevice_status_image And here works everything... So, it open up a dialog. 一切都在这里进行...因此,它打开了一个对话框。 That means that ClassA.this.getParent() is good and it works. 这意味着ClassA.this.getParent()很好并且可以正常工作。 And you can see, I call db.getAllIconsOfOldCategory() where I set new adapter. 您会看到,我在设置新适配器的地方调用了db.getAllIconsOfOldCategory()

device_status_image.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            final Dialog dialog = new Dialog(ClassA.this
                    .getParent());
            dialog.setContentView(R.layout.list_view_icon);
            listView = (ListView) dialog.findViewById(R.id.list_view);

            IconAdapter adapter = new IconAdapter(inflater, light.id,
                    light.oldCategory, light.name, db
                            .getAllIconsOfOldCategory(light.oldCategory));    

            listView.setAdapter(adapter);
            dialog.show();

            Button bCancel = (Button) dialog.findViewById(R.id.bCancel);
            bCancel.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    dialog.dismiss();

                }
            });

        }
    });

So, I tried to add String icon = db.getIcon(light.id, settings.getLastPkAccessPoint(), status, light.oldCategory); 因此,我尝试添加String icon = db.getIcon(light.id, settings.getLastPkAccessPoint(), status, light.oldCategory); into OnClickListener, just to check if here the method execute (I check this with debugging) and it worked, the method getIcon() executed... But, when I put it back to the place where it need to be. 进入OnClickListener,只是要检查方法是否在这里执行(我通过调试对其进行检查)并且是否有效,方法getIcon()执行...但是,当我将其放回需要的位置时。 Surprise, surprise, it don't work any more.. 惊喜,惊喜,它不再起作用了。

And, here is log file, if it will help you. 而且,这是日志文件,如果有帮助的话。 Thanks! 谢谢! It is very long. 很长

09-16 01:35:59.167: E/AndroidRuntime(28019): FATAL EXCEPTION: main
09-16 01:35:59.167: E/AndroidRuntime(28019): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.android/com.mysite.mobile.LightsActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.android/com.mysite.mobile.classA}: java.lang.NullPointerException
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2194)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:1991)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:703)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost.setCurrentTab(TabHost.java:350)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:540)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.view.View.performClick(View.java:3549)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.view.View$PerformClick.run(View.java:14393)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.os.Handler.handleCallback(Handler.java:605)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.os.Looper.loop(Looper.java:154)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.main(ActivityThread.java:4945)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at java.lang.reflect.Method.invokeNative(Native Method)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at java.lang.reflect.Method.invoke(Method.java:511)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at dalvik.system.NativeStart.main(Native Method)
09-16 01:35:59.167: E/AndroidRuntime(28019): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.android/com.mysite.mobile.classA}: java.lang.NullPointerException
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2194)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:1991)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:703)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost.setCurrentTab(TabHost.java:350)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.widget.TabHost.addTab(TabHost.java:240)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.LightsActivity.changeDeviceTabs(LightsActivity.java:34)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.LightsActivity.onCreate(LightsActivity.java:19)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.Activity.performCreate(Activity.java:4531)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
09-16 01:35:59.167: E/AndroidRuntime(28019):    ... 18 more
09-16 01:35:59.167: E/AndroidRuntime(28019): Caused by: java.lang.NullPointerException
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.classA.renderDevice(classA.java:89)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.MyViewDeviceActivity.renderDevices(MyViewDeviceActivity.java:58)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.MyViewDeviceActivity.onCreate(MyViewDeviceActivity.java:30)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at com.mysite.mobile.classA.onCreate(classA.java:38)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.Activity.performCreate(Activity.java:4531)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
09-16 01:35:59.167: E/AndroidRuntime(28019):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
09-16 01:35:59.167: E/AndroidRuntime(28019):    ... 29 more

From what I can tell in your logs, you should check that 'light' and Settings.getInstance() aren't null. 根据我在日志中看到的信息,应该检查“ light”和Settings.getInstance()是否不为null。 The reason why it would work in your onClickListener and not in that method is probably because they get instantiated somewhere before you click the image but not before renderDevice() is called. 之所以可以在您的onClickListener中而不在该方法中工作,可能是因为它们在您单击图像之前(而不是在调用renderDevice()之前)被实例化。

Try doing something like this in your renderDevice() method: 尝试在renderDevice()方法中执行以下操作:

ImageView device_status_image = (ImageView) lightView
            .findViewById(R.id.device_status_image);
    Settings settings = Settings.getInstance();

    if( light == null)
    {
       /* instantiate your light variable */
    }

    if ( settings == null )
    {
      /* write the necessary code to make sure your singleton gets created */
    }  
    String icon = db.getIcon(light.id, settings.getLastPkAccessPoint(), status, light.oldCategory);

    if ( icon != null) {
        int resId = getResources().getIdentifier(icon, "drawable",
                getPackageName());
        device_status_image.setImageResource(resId);
    } else
        device_status_image.setImageResource(R.drawable.normal_icon); 

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用SQLiteOpenHelper时ContextWrapper.openOrCreateDatabase中的NullPointerException - NullPointerException in ContextWrapper.openOrCreateDatabase when using SQLiteOpenHelper 在主活动中使用SQLiteOpenHelper类访问数据库 - Database using SQLiteOpenHelper Class accessing in main activity SQLiteOpenHelper中的onDowngrade()(或降级时不会崩溃的另一种方式) - onDowngrade() in SQLiteOpenHelper (or another way to not crash when downgrading) android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)nullpointerexception - android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252) nullpointerexception android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)中的java.lang.NullPointerException - java.lang.NullPointerException at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224) 尝试从SQLiteOpenHelper检索数据时出现Android NullpointerException - Android NullpointerException when trying to retrieve data from SQLiteOpenHelper 从AsyncTask触发时,SQLiteOpenHelper.getWritableDatabase上的NullPointerException - NullPointerException on SQLiteOpenHelper.getWritableDatabase when triggered from AsyncTask 创建时出现SQLiteOpenHelper NullPointerException - SQLiteOpenHelper NullPointerException on creation 访问ActionBar时为nullPointerException - nullPointerException when accessing ActionBar 访问构造函数时发生NullPointerException - NullPointerException when accessing constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM