【问题标题】:Cannot access another class in android无法访问android中的另一个类
【发布时间】:2011-06-03 14:30:53
【问题描述】:

我对我的简单代码发生的事情感到困惑。即使我检查了代码流,它也不会进入另一个类文件。以下是我在android中的代码:

公共类 MedF1 扩展 ListActivity {

DrugsDbAdapter drugsDbAdapter = new DrugsDbAdapter(this);
DrugsDbAdapter.myDbHelper mDbHelper = new DrugsDbAdapter.myDbHelper(this);

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



    try {

        mDbHelper.createDataBase();

        } catch (IOException ioe) {

        throw new Error("Unable to create database");

        }

        try {

        mDbHelper.openDataBase();

        }catch(SQLException sqle){

        throw sqle;

        }

        populateDrugList();

}

public void populateDrugList() {

    Cursor drugListCursor = drugsDbAdapter.getAllEntries();

    startManagingCursor (drugListCursor);

    String[] from = new String[] {DrugsDbAdapter.KEY_DRUG};

    int[] to = new int[] {R.id.text1};

    SimpleCursorAdapter drugs = new SimpleCursorAdapter(this, R.layout.drug_row, drugListCursor, from, to);

    setListAdapter(drugs);
}

数据库适配器类在下面,代码只是没有超出上面代码中populateDrugList()的druglistCursor!

public class DrugsDbAdapter {

private static final String DATABASE_TABLE = "data";


//The index column name for use in where clauses
public static final String KEY_ID = "_id";

//The name and column index of each column in DB
public static final String KEY_DRUG = "drug";
public static final String KEY_CONTENT = "content";
public static final String KEY_INDICATION = "indication";
public static final String KEY_DOSAGE = "dosage";
public static final String KEY_SPECIALPRECAUTION = "specialprecaution";


//variable to hold the database instance
private static SQLiteDatabase db;
//Context of the application using the database
private final Context context;
//Database open/upgrade helper
private myDbHelper dbHelper;

public DrugsDbAdapter(Context _context) {

    this.context = _context;

}

public void open() throws SQLiteException {
    try {
        db = dbHelper.getWritableDatabase();
    } catch (SQLiteException ex) {
        db = dbHelper.getReadableDatabase();
    }
}

//Creation of database and basic parameters
public static class myDbHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "data/data/com.paad.MedF1/databases/";

    private static String DB_NAME = "data.sqlite";

    private SQLiteDatabase myDataBase;

    private Context myContext;

    public  myDbHelper (Context context) {

        super(context, DB_NAME, null, 1);

        this.myContext = context;

    }

    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist) {
            // do nothing
        } else {

            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error ("Error copying database");

            }

        }
    }

    private boolean checkDataBase(){


        boolean checkDB = false;

        try{
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);

            checkDB = dbfile.exists();

        }catch(SQLiteException e){

            //database does't exist yet.

        }

        return checkDB;

    }


    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


public void close() {
    db.close();
}

public long insertEntry(myDrug _myDrug) {

    ContentValues newDrugValues = new ContentValues();

    newDrugValues.put(KEY_DRUG, _myDrug.getDrug());
    newDrugValues.put(KEY_CONTENT, _myDrug.getContent());
    newDrugValues.put(KEY_INDICATION, _myDrug.getIndication());
    newDrugValues.put(KEY_DOSAGE, _myDrug.getDosage());
    newDrugValues.put(KEY_SPECIALPRECAUTION, _myDrug.getSpecialprecaution());

    return db.insert(DATABASE_TABLE, null, newDrugValues);
}

public boolean removeEntry (long _rowIndex) {
    return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
}

public Cursor getAllEntries () { 
    return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_DRUG, KEY_CONTENT, KEY_INDICATION, KEY_DOSAGE, KEY_SPECIALPRECAUTION}, null, null, null, null, null);
}


}   

救命!!!我的 logcat 输出是:

06-03 22:29:01.636: ERROR/AndroidRuntime(1424): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paad.MedF1/com.paad.MedF1.MedF1}: java.lang.NullPointerException
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.os.Looper.loop(Looper.java:123)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at java.lang.reflect.Method.invokeNative(Native Method)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at java.lang.reflect.Method.invoke(Method.java:521)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at dalvik.system.NativeStart.main(Native Method)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424): Caused by: java.lang.NullPointerException
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at com.paad.MedF1.MedF1.populateDrugList(MedF1.java:51)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at com.paad.MedF1.MedF1.onCreate(MedF1.java:45)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-03 22:29:01.636: ERROR/AndroidRuntime(1424):     ... 11 more

【问题讨论】:

  • 您是否将活动包含在清单中?
  • MedF1.java 中第 45 行和第 51 行之间的内容

标签: android class nullpointerexception


【解决方案1】:

您的 drugDbAdapter 为空。您只声明了DrugsDbAdapterdrugsDbAdapter;,但您需要实例化它。

【讨论】:

  • 您好丹尼尔,谢谢您的回复!我如何实例化它?我在这方面很糟糕......有什么地方可以让我了解更多吗?
  • 看到DrugsDbAdapter的源码之前很难说。尝试在 onCreate 方法中创建一个新实例,drugsDbAdapter = new DrugsDbAdapter()。构造函数很可能需要数据库助手,它可能由构造函数参数或其他方法提供。没有看到其他代码就无法回答这个问题。但是如果你检查代码应该很明显。
  • 嗨丹尼尔,我已经编辑并包含了另一半代码,并在上面代码的开头尝试了实例化,但仍然无济于事......可能还有其他潜在问题吗?会不会是班级问题?我已经实例化了两次,会不会有问题?
  • @jamen 尝试从developer.android.com/guide/topics/ui/binding.html的“使用 AdapterView 绑定数据”参考开始
  • @Joe,谢谢!你是说显示器有问题?稍后我会看一下 :) 但是现在我一直在调试器中,整个代码在 populateDrugList 的 getAllEntries 处停止,这很奇怪,因为我检查了上下文“this”并且它完全匹配一个工作代码..
【解决方案2】:

您是否初始化了drugDbAdapter?我在您的代码中的任何地方都看不到初始化。

【讨论】:

  • 谢谢马克!什么是实例化?我在这方面真的很糟糕......我怎样才能实例化drugDbAdapter?
【解决方案3】:

这看起来就像我每次在我的 Activity 的布局 XML 中出现错误时都会遇到的错误。检查以确保 XML 格式正确且正确。将其简化为最简单的状态并对其进行测试以确保这不是问题。

另外,正如其他人所说,给出的代码看起来不像您实例化了 db 适配器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2011-04-03
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多