0

我的 android/java 代码有问题。当我从一项活动切换到另一项活动时,我只是得到了错误。我确定问题是数据库。堆栈跟踪中的主要错误是活动空指针和未明确关闭的数据库。任何人都可以就这个问题给我一些帮助吗?

有人熟悉下面的错误跟踪吗?

问题是,我有两种方法可以访问我也想访问的页面。通过快捷方式,当我第一次加载应用程序时,下一个按钮会给我错误。但是当我完成编辑时,到达我想要的页面并返回。然后第一个“下一个”起作用。太烦人了!

这是 logcat 中的跟踪:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.sec/com.android.sec.TabLayoutActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.sec/com.android.sec.RoomOverview}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
04-15 20:37:05.333: E/AndroidRuntime(568):  at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.sec/com.android.sec.RoomOverview}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
at android.widget.TabHost.setCurrentTab(TabHost.java:323)
at android.widget.TabHost.addTab(TabHost.java:213)
at com.android.sec.TabLayoutActivity.onCreate(TabLayoutActivity.java:30)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
... 11 more
E/AndroidRuntime(568): Caused by: java.lang.NullPointerException
at com.android.sec.RoomOverview.onCreate(RoomOverview.java:106)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
E/AndroidRuntime(568):  ... 20 more

这是引发错误的类:

package com.android.sec;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class RoomOverview extends Activity {

    public String value = CreateClient.getName();
    public String status = CreateRoom.getStatus();
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;
    public Cursor c, c2, c3, c4, c5, c6;
    SQLiteDatabase sampleDB;
    public static String selectedItem;
    ImageButton edit, delete;
    final Context context = this;
    public String typeToDelete;
    public static String getID[];

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.roomoverview);

        edit = (ImageButton) findViewById(R.id.editButton);
        edit.setEnabled(false);
        edit.setAlpha(127);

        delete = (ImageButton) findViewById(R.id.deleteButton);
        delete.setEnabled(false);
        delete.setAlpha(127);

        lvItem = (ListView)this.findViewById(R.id.listView1);
        lvItem.setTextFilterEnabled(true);

        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.single_item,itemArrey);
        lvItem.setAdapter(itemAdapter);

        if(value == "Retrieve"){

            sampleDB = getBaseContext().openOrCreateDatabase(ClientList.retrievedClient+".db", MODE_PRIVATE, null);
        } 
        else if (value == "Create"){

            sampleDB = getBaseContext().openOrCreateDatabase(CreateClient.createdClient+".db", MODE_PRIVATE, null);
        }


        if(status == "Edit"){

            TextView roomName = (TextView) findViewById(R.id.roomName);
            roomName.append(EditRoom.possiblyEditedRoom);
            c = sampleDB.rawQuery("SELECT * FROM tbl_plant WHERE r_id =?", new String[] {RoomList.r_id});   
            c2 = sampleDB.rawQuery("SELECT * FROM tbl_windowData WHERE r_id =?", new String[] {RoomList.r_id}); 
            c3 = sampleDB.rawQuery("SELECT * FROM tbl_itData WHERE r_id =?", new String[] {RoomList.r_id}); 
            c4 = sampleDB.rawQuery("SELECT * FROM tbl_otherData WHERE r_id =?", new String[] {RoomList.r_id});  
            c5 = sampleDB.rawQuery("SELECT * FROM tbl_heatingData WHERE r_id =?", new String[] {RoomList.r_id});    
            c6 = sampleDB.rawQuery("SELECT * FROM tbl_lightingData WHERE r_id =?", new String[] {RoomList.r_id});   
        } 
        else if (status == "Create"){

            TextView roomName = (TextView) findViewById(R.id.roomName);
            roomName.append(CreateRoom.selectedRoom);
            c = sampleDB.rawQuery("SELECT * FROM tbl_plant WHERE r_id =?", new String[] {CreateRoom.r_id}); 
            c2 = sampleDB.rawQuery("SELECT * FROM tbl_windowData WHERE r_id =?", new String[] {CreateRoom.r_id});
            c3 = sampleDB.rawQuery("SELECT * FROM tbl_itData WHERE r_id =?", new String[] {CreateRoom.r_id});   
            c4 = sampleDB.rawQuery("SELECT * FROM tbl_otherData WHERE r_id =?", new String[] {CreateRoom.r_id});    
            c5 = sampleDB.rawQuery("SELECT * FROM tbl_heatingData WHERE r_id =?", new String[] {CreateRoom.r_id});
            c6 = sampleDB.rawQuery("SELECT * FROM tbl_lightingData WHERE r_id =?", new String[] {CreateRoom.r_id});     
        }

        itemArrey.add("---------- Plant ----------");
        if (c != null ) {
            if  (c.moveToFirst()) {
                do {

                    String id = c.getString(c.getColumnIndex("p_id"));
                    String plantName = c.getString(c.getColumnIndex("itemName"));
                    String plantType = c.getString(c.getColumnIndex("itemType"));
                    itemArrey.add("Plant Name: "+plantName+"\n"+"Type: "+plantType+"\n"+"ID: #"+id);

                }while (c.moveToNext());
            }
        }
        c.close();

Multiple of the above i.e. c2, c3, c4 etc. etc. - saves reading 

        lvItem.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text

                selectedItem = (String) ((TextView) view).getText();
                if(selectedItem.contains("----------")){}

                else {
                    edit.setEnabled(true);
                    edit.setAlpha(255);
                    delete.setEnabled(true);
                    delete.setAlpha(255);

                //Toast.makeText(getApplicationContext(), "item: "+selectedItem+" child: "+parent.getCount(), Toast.LENGTH_LONG).show();
                for(int a = 0; a < parent.getChildCount(); a++)
                {
                    parent.getChildAt(a).setBackgroundColor(Color.WHITE);
                } 

                view.setBackgroundColor(Color.parseColor("#97C361"));

                }
            }
        });

        edit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                if(selectedItem.contains("----------")){}

                else {

                sampleDB.close();

                if(selectedItem.startsWith("Plant Name:")){
                    typeToDelete = "P";
                } 
                else if (selectedItem.startsWith("Type:")){
                    typeToDelete = "W";
                } 
                else if (selectedItem.startsWith("PC Quantity:")){
                    typeToDelete = "I";
                } 
                else if (selectedItem.startsWith("Other Name:")){
                    typeToDelete = "O";
                } 
                else if (selectedItem.startsWith("Heating Type:")){
                    typeToDelete = "H";
                } 
                else if (selectedItem.startsWith("Lighting Type:")){
                    typeToDelete = "L";
                } 

                getID = selectedItem.split("#");

                if(typeToDelete == "P"){

                    Intent intent2 = new Intent(RoomOverview.this, EditPlant.class);
                    startActivityForResult(intent2, 0);

                } 
                else if (typeToDelete == "W"){

                    Intent intent2 = new Intent(RoomOverview.this, EditWindows.class);
                    startActivityForResult(intent2, 0);

                } 
                else if (typeToDelete == "I"){

                    Intent intent2 = new Intent(RoomOverview.this, EditIT.class);
                    startActivityForResult(intent2, 0);

                } 
                else if (typeToDelete == "O"){

                    Intent intent2 = new Intent(RoomOverview.this, EditOther.class);
                    startActivityForResult(intent2, 0);

                } 
                else if (typeToDelete == "H"){

                    Intent intent2 = new Intent(RoomOverview.this, EditHeating.class);
                    startActivityForResult(intent2, 0);

                } 
                else if (typeToDelete == "L"){

                    Intent intent2 = new Intent(RoomOverview.this, EditLighting.class);
                    startActivityForResult(intent2, 0);

                    }
                }
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                if(selectedItem.contains("----------")){}

                else {

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                alertDialogBuilder.setTitle("Delete:");

                alertDialogBuilder.setMessage("Are you sure?").setCancelable(false).setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        //delete building

                        if(selectedItem.startsWith("Plant Name:")){
                            typeToDelete = "P";
                        } 
                        else if (selectedItem.startsWith("Type:")){
                            typeToDelete = "W";
                        } 
                        else if (selectedItem.startsWith("PC Quantity:")){
                            typeToDelete = "I";
                        } 
                        else if (selectedItem.startsWith("Other Name:")){
                            typeToDelete = "O";
                        } 
                        else if (selectedItem.startsWith("Heating Type:")){
                            typeToDelete = "H";
                        } 
                        else if (selectedItem.startsWith("Lighting Type:")){
                            typeToDelete = "L";
                        } 

                        String getID[] = selectedItem.split("#");

                        if(typeToDelete == "P"){
                            sampleDB.delete("tbl_plant", "p_id =?", new String[] {getID[1]});  
                        } 
                        else if (typeToDelete == "W"){
                            sampleDB.delete("tbl_windowData", "w_id =?", new String[] {getID[1]});  
                        } 
                        else if (typeToDelete == "I"){
                            sampleDB.delete("tbl_itData", "i_id =?", new String[] {getID[1]});  
                        } 
                        else if (typeToDelete == "O"){
                            sampleDB.delete("tbl_otherData", "o_id =?", new String[] {getID[1]});  
                        } 
                        else if (typeToDelete == "H"){
                            sampleDB.delete("tbl_heatingData", "h_id =?", new String[] {getID[1]});  
                        } 
                        else if (typeToDelete == "L"){
                            sampleDB.delete("tbl_lightingData", "l_id =?", new String[] {getID[1]});  
                        }

                        sampleDB.close();

                        Intent intent2 = new Intent(RoomOverview.this, TabLayoutActivity.class);
                        startActivityForResult(intent2, 0);     
            }
        })
        .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        //do nothing
                        dialog.cancel();
                    }
                });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
            }});      
    }
}
4

3 回答 3

2

首先不要用...

if (value == "Retrieve") { ...

if (value == "Create") { ...

if (status == "Edit") { ...

...因为这在 Java 中不起作用。采用 ...

if ("Retrieve".equals(value)) { ...

if ("Create".equals(value)) { ...

if ("Edit".equals(status)) { ...

... 反而。因此,您的光标c很可能是null. 这不会是一个问题,如果你把你的陈述放在c.close()里面。if因此,其次将您的close()方法调用移动到if语句中:

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
           ...

        } while (c.moveToNext());
    }
    c.close(); // move to here
}
// here, close() is outside of the if causing a NPE if c is null

即使这可能无法解决所有问题-这至少是一个开始,我希望它有所帮助;)

干杯!

于 2013-04-15T21:04:00.873 回答
1

您只需要确保在使用后关闭游标和 dbHelper 对象。即 cursor.close() 或 dbHelper.close()...等。

此外,我建议您使用扩展 SQLiteOpenHelper 的类。然后,您可以使用该帮助程序来获取对 SQLiteDatabase 的引用,

SQLiteDatabase db = dbHelper.getWritableDatabase();
//db.query(....)
//db.select(....)
etc...

有很多关于这个的教程。

于 2013-04-15T19:58:17.203 回答
1

异常源自第 106 行,试图关闭一个为空的游标。进行检查或移动调用以将光标关闭到前面的检查 (c != null)。

于 2013-04-15T20:58:11.350 回答