Context是Null,所以我无法打开数据库

时间:2013-11-20 11:56:33

标签: android database android-sqlite

我尝试打开一个数据库。但它说上下文为空,无法打开数据库。 ı试着找到为什么它是这样但不冷静。拜托,你能告诉我哪里错了。

这是无法打开的数据库类;

package com.bilge.aysonu;

public class DecisionDatabase {

public static final String TAG = DbHelperTemporary2.class.getSimpleName();
public static final String DB_NAME = "aySonuDecisionDB.sql";
private static int DB_PATH = R.string._data_data_com_bilge_aysonu_assets_;
public static final int DB_VERSION = 1;
public static final String DB_TABLE = "decision";

public static final String C_ID = "c_id";// Special for id
public static final String C_DECISION = "dialogDecision";

public static final String CREATE_TABLE = "CREATE TABLE decision (c_id integer primary key autoincrement, "
        + "dialogDecision integer);";

private DbHelperTemporary2 dbHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

public static class DbHelperTemporary2 extends SQLiteOpenHelper {

    public DbHelperTemporary2(Context context) {

        super(context, DB_NAME, null, DB_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        Log.d(TAG, "onCreate sql: " + CREATE_TABLE);
        db.execSQL(CREATE_TABLE);
    }

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

        db.execSQL("drop table if exists " + DB_TABLE);
        Log.w(TAG, "onUpdate drop table " + DB_TABLE);
        onCreate(db);
    }

}

public DecisionDatabase(Context c) {

        ourContext = c;
        if(ourContext == null)
            Log.i(TAG, "DecisionDatabaseContextNull");
        else Log.i(TAG, "DecisionDatabaseConstructor");
}

public void openDatabase() throws SQLException {
    ourDatabase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
            SQLiteDatabase.OPEN_READWRITE);
}

public void open() throws NumberFormatException {

    try {
        dbHelper = new DbHelperTemporary2(ourContext);
        ourDatabase = dbHelper.getWritableDatabase();
        Log.i(TAG, "DecisionDatabaseOpen");
        return;
    } catch (Exception e) {
        Log.d(TAG, "Couldn't open database " + DB_NAME);
        e.printStackTrace();
    } finally {

    }
}

public void close() {

    dbHelper.close();
    ourDatabase.close();
}
public void delete (){
    if(ourDatabase!=null)
        ourDatabase.delete(DB_TABLE, null, null);
}

public void EntryDecision(int decision) {
    int decisionentry=decision;
    ContentValues cv = new ContentValues();
    cv.put(C_DECISION, decisionentry);
    ourDatabase.insert(DB_TABLE, null, cv);
    cv.clear();
    Log.i(TAG, "DecisionDatabaseEntryDecision");
}

public int getDecisionData() {
    Cursor c = ourDatabase.query(DB_TABLE, null, null, null, null, null,
            null);
    String[] result = new String[1];

    int i_decision = c.getColumnIndex(C_DECISION);
    if (c.moveToFirst()) {
        result[0] = c.getString(i_decision);
    } else
        result[0] = "2";
    c.close();
    Log.i(TAG, "DecisionDatabaseGetDecisionData");
    return Integer.parseInt(result[0]);
}

}

这是主要的课程;

package com.bilge.aysonu;

public class Main extends FragmentActivity {

EditText bakici, arabaKredisi, ogrenimKredisi, tatilKredisi, elektrik;
EditText su, internet, aidat, kasko, digerTaksitler;
EditText diger, maasSelo, maasHilal, digerGelirler;
TextView toplamGelir, toplamHarcama, eldeKalan;
Spinner yil, ay;
LinearLayout row17, row18, row19;
TemporaryDatabase tdb;
AySonuDatabase aDb;
DecisionDatabase dDb;
MainFragment mainFragment = new MainFragment();
FragmentTransaction transaction = getSupportFragmentManager()
        .beginTransaction();;
private final String TAG = this.getClass().getSimpleName();
int toplamgelir, toplamharcama = 0, eldekalan = 0;
int bakicii, arabakredisi, ogrenimkredisi, tatilkredisi, elektrikk;
int suu, internett, aidatt, kaskoo, digergelirler, maasselo, maashilal;
int digertaksitler, digerr, yil2;
String ay2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Widget tanımlamaları
    toplamGelir = (TextView) findViewById(R.id.editTextToplamGelir);
    digerGelirler = (EditText) findViewById(R.id.editTextDigerGelirler);
    toplamHarcama = (TextView) findViewById(R.id.editTextToplamHarcama);
    diger = (EditText) findViewById(R.id.editTextDiger);
    digerTaksitler = (EditText) findViewById(R.id.editTextDigerTaksitler);
    kasko = (EditText) findViewById(R.id.editTextKaskoSigorta);
    aidat = (EditText) findViewById(R.id.editTextAidat);
    internet = (EditText) findViewById(R.id.editTextFaturaInternet);
    su = (EditText) findViewById(R.id.editTextFaturaSu);
    elektrik = (EditText) findViewById(R.id.editTextFaturaElektrik);
    tatilKredisi = (EditText) findViewById(R.id.editTextTatilKredisi);
    ogrenimKredisi = (EditText) findViewById(R.id.editTextOgrenimKredisi);
    arabaKredisi = (EditText) findViewById(R.id.editTextKrediAraba);
    bakici = (EditText) findViewById(R.id.editTextBakici);
    eldeKalan = (TextView) findViewById(R.id.editTextEldeKalan);
    maasSelo = (EditText) findViewById(R.id.editTextMaasSelo);
    maasHilal = (EditText) findViewById(R.id.editTextMaasHilal);
    yil = (Spinner) findViewById(R.id.spinnerYillar);
    ay = (Spinner) findViewById(R.id.spinnerAylar);
    row17 = (LinearLayout) findViewById(R.id.tableRow17);
    row18 = (LinearLayout) findViewById(R.id.tableRow18);
    row19 = (LinearLayout) findViewById(R.id.tableRow19);

    // Button etki tepkileri
    Button hesapla, getir, kaydet;
    hesapla = (Button) findViewById(R.id.buttonHesapla);
    getir = (Button) findViewById(R.id.buttonGetir);
    kaydet = (Button) findViewById(R.id.buttonKaydet);
    kaydet.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            kaydeden();

        }
    });
    hesapla.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            hesaplayan();

        }
    });
    getir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            int yil2 = Integer.valueOf(yil.getSelectedItem().toString());
            String ay2 = ay.getSelectedItem().toString();
            tdb.Entry(yil2, ay2);
            row17.setVisibility(1);
            row18.setVisibility(1);
            row19.setVisibility(1);
            if (mainFragment != null)
                transaction.remove(mainFragment);
            fragment();
        }

    });
    Log.i(TAG, "mainonCreate");
}

// Bütçe hesaplamalarını veritabanına kaydeden yordam.
protected void kaydeden() {

    boolean didItWork = false;
    boolean isDataInDatabase = false;
    int i;
    try {

        yil2 = Integer.valueOf(yil.getSelectedItem().toString());
        ay2 = ay.getSelectedItem().toString();
        isDataInDatabase = aDb.Entry(yil2, ay2, bakicii, arabakredisi,
                ogrenimkredisi, tatilkredisi, elektrikk, suu, internett,
                aidatt, kaskoo, digertaksitler, digerr, maasselo,
                maashilal, digergelirler, toplamharcama, toplamgelir,
                eldekalan);
        if (isDataInDatabase) {
            MyDialogFragment testDialog = new MyDialogFragment();
            FragmentManager fm = getSupportFragmentManager();
            testDialog.setRetainInstance(true);
            testDialog.show(fm, "MyDialogFragment");
            dDb.open();
            i = dDb.getDecisionData();
            switch (i) {
            case 0:
                aDb.EntryWithoutDialog(yil2, ay2, bakicii, arabakredisi,
                        ogrenimkredisi, tatilkredisi, elektrikk, suu,
                        internett, aidatt, kaskoo, digertaksitler, digerr,
                        maasselo, maashilal, digergelirler, toplamharcama,
                        toplamgelir, eldekalan);
                didItWork = true;
                break;
            default:
                break;
            }
        } else
            didItWork = true;

    } catch (Exception e) {
        didItWork = false;
        Log.i("Log", e.getMessage() + "Error!");
    } finally {
        if (didItWork)
            Toast.makeText(Main.this, "DBEntrySucceed", Toast.LENGTH_LONG)
                    .show();
        else
            Toast.makeText(Main.this, "NoDBEntry", Toast.LENGTH_LONG)
                    .show();
        Log.i(TAG, "mainKaydeden");
    }
}

// Seçilen ay ve yılın bütçesini ekrana fragment yardımıyla yazdıran yordam.
public void fragment() {
    try {

        transaction.add(R.id.mainLinLay, mainFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        // Log
        Log.i(TAG, "mainfragment");
    } catch (Exception e) {
        // TODO: handle exception
        Log.i(TAG, "mainfragmentException");
    } finally {

    }
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    aDb = new AySonuDatabase(Main.this);
    aDb.open();

    tdb = new TemporaryDatabase(Main.this);
    tdb.open();

    dDb = new DecisionDatabase(Main.this);
    dDb.open();
    Log.i(TAG, "mainonResume");
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mainmenu, menu);
    Log.i(TAG, "mainonCreateOptionsMenu");
    return true;
}

}

这是DialogFragment类;

package com.bilge.aysonu;

public class MyDialogFragment extends DialogFragment{
Context mContext=getActivity();
boolean decision; 
DecisionDatabase dDb=new DecisionDatabase(mContext);

int i;
private final String TAG =  this.getClass().getSimpleName();
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle("Aynı tarihli kayit var!!!");
    alertDialogBuilder.setMessage("Kaydetmek istediğinizden emin misiniz?");
    dDb.open();

    //null should be your on click listener
    alertDialogBuilder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            i=0;
            dDb.EntryDecision(i);
            dDb.close();
            dialog.dismiss();

        }
    });
    alertDialogBuilder.setNegativeButton("Hayır", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            i=1;
            dDb.EntryDecision(i);
            dDb.close();
            dialog.dismiss(); 
        }
    });

    Log.i(TAG, "MyDialogFragmentOnCreateDialog");
    return alertDialogBuilder.create();
}
@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    dDb.close();

    Log.i(TAG, "MyDialogFragmentOnStop");
}
@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    Log.i(TAG, "MyDialogFragmentOnStart");      
}

}

这是LogCat;

   11-20 11:15:33.310: I/Main(407): mainonCreate
11-20 11:15:33.330: I/DatabaseHelper(407): AysonuDatabaseConstructor
11-20 11:15:33.390: I/DatabaseHelper(407): AysonuDatabaseOpen
11-20 11:15:33.390: I/DbHelperTemporary(407): TemporaryDatabaseConstructor
11-20 11:15:33.420: I/DbHelperTemporary(407): TemporaryDatabaseOpen
11-20 11:15:33.420: I/DbHelperTemporary2(407): DecisionDatabaseConstructor
11-20 11:15:33.450: I/DbHelperTemporary2(407): DecisionDatabaseOpen
11-20 11:15:33.450: I/Main(407): mainonResume
11-20 11:15:46.911: W/KeyCharacterMap(407): No keyboard for id 0
11-20 11:15:46.922: W/KeyCharacterMap(407): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
11-20 11:16:16.191: I/Main(407): mainHesaplayan
11-20 11:16:18.281: I/DatabaseHelper(407): AysonuDatabaseEntryElse
11-20 11:16:18.301: I/Main(407): mainKaydeden
11-20 11:16:32.012: D/dalvikvm(407): GC_FOR_MALLOC freed 6036 objects / 277368 bytes in 174ms
11-20 11:16:35.671: I/DatabaseHelper(407): AysonuDatabaseEntryIf
I/DbHelperTemporary2(407): DecisionDatabaseContextNull
I/DbHelperTemporary2(407): DecisionDatabaseOpen
I/DbHelperTemporary2(407): DecisionDatabaseGetDecisionData
I/Main(407): mainKaydeden
D/DbHelperTemporary2(407): Couldn't open database aySonuDecisionDB.sql
W/System.err(407): java.lang.NullPointerException
W/System.err(407):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
W/System.err(407):  at com.bilge.aysonu.DecisionDatabase.open(DecisionDatabase.java:71)
W/System.err(407):  at com.bilge.aysonu.MyDialogFragment.onCreateDialog(MyDialogFragment.java:23)
W/System.err(407):  at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:295)
W/System.err(407):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
W/System.err(407):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
W/System.err(407):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
W/System.err(407):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
W/System.err(407):  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
W/System.err(407):  at android.os.Handler.handleCallback(Handler.java:587)
W/System.err(407):  at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err(407):  at android.os.Looper.loop(Looper.java:123)
W/System.err(407):  at android.app.ActivityThread.main(ActivityThread.java:4627)
W/System.err(407):  at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(407):  at java.lang.reflect.Method.invoke(Method.java:521)
W/System.err(407):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
W/System.err(407):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
W/System.err(407):  at dalvik.system.NativeStart.main(Native Method)
I/MyDialogFragment(407): MyDialogFragmentOnCreateDialog
I/MyDialogFragment(407): MyDialogFragmentOnStart
D/AndroidRuntime(407): Shutting down VM
W/dalvikvm(407): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
E/AndroidRuntime(407): FATAL EXCEPTION: main
E/AndroidRuntime(407): java.lang.NullPointerException
E/AndroidRuntime(407):  at com.bilge.aysonu.DecisionDatabase.EntryDecision(DecisionDatabase.java:96)
E/AndroidRuntime(407):  at com.bilge.aysonu.MyDialogFragment$1.onClick(MyDialogFragment.java:31)
E/AndroidRuntime(407):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
E/AndroidRuntime(407):  at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(407):  at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(407):  at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(407):  at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(407):  at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(407):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(407):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(407):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

试试这种方式

  1. 删除此行Context mContext=getActivity();
  2. 用{替换DecisionDatabase dDb=new DecisionDatabase(mContext); DecisionDatabase dDb;
  3. 在您的onCreateDialog()方法中添加此行
  4. dDb=new DecisionDatabase(getActivity());

答案 1 :(得分:0)

如果你想获得(父 - )活动的上下文,你需要这样做:

 Context context = getActivity().getBaseContext();