来自SQLite类的java.lang.NullPointerException在访问android中的数据库时

时间:2013-05-22 12:26:05

标签: java android sqlite android-fragments

我是Android的新手。我正试图通过getDataMain()方法从数据库中获取数据。当我运行我的应用程序时,它会给出一个java.lang.NullPointerException。我找不到问题所在?你能帮帮我吗?

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainFragment extends Fragment {

TextView bakici;
TextView arabaKredisi;
TextView ogrenimKredisi;
TextView tatilKredisi;
TextView elektrik;
TextView su;
TextView internet;
TextView aidat;
TextView kasko;
TextView digerTaksitler;
TextView diger;
TextView maasSelo;
TextView maasHilal;
TextView digerGelirler;
TextView toplamGelir;
TextView toplamHarcama;
TextView eldeKalan;

private final String TAG =  this.getClass().getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Log.i(TAG, "mainFragmentonCreate");

}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.maingetirgoster,
            container, false);
    toplamGelir = (TextView) view.findViewById(R.id.textToplamGelir2);
    digerGelirler = (TextView) view.findViewById(R.id.textDigerGelirler2);
    toplamHarcama = (TextView) view.findViewById(R.id.textToplamHarcama2);
    diger = (TextView) view.findViewById(R.id.textDiger2);
    digerTaksitler = (TextView) view.findViewById(R.id.textDigerTaksitler2);
    kasko = (TextView) view.findViewById(R.id.textKaskoSigorta2);
    aidat = (TextView) view.findViewById(R.id.textAidat2);
    internet = (TextView) view.findViewById(R.id.textFaturaInternet2);
    su = (TextView) view.findViewById(R.id.textFaturaSu2);
    elektrik = (TextView) view.findViewById(R.id.textFaturaElektrik2);
    tatilKredisi = (TextView) view.findViewById(R.id.textTatilKredisi2);
    ogrenimKredisi = (TextView)view.findViewById(R.id.textOgrenimKredisi2);
    arabaKredisi = (TextView) view.findViewById(R.id.textKrediAraba2);
    bakici = (TextView) view.findViewById(R.id.textButtonBakici2);
    eldeKalan = (TextView) view.findViewById(R.id.textEldeKalan2);
    maasSelo = (TextView) view.findViewById(R.id.textMaasSelo2);
    maasHilal = (TextView) view.findViewById(R.id.textMaasHilal2);

    Context context=getActivity();

    TemporaryDatabase tdb= new TemporaryDatabase(context);
    tdb.open();
    String[] result2= new String[2];
    result2=tdb.getData();
    tdb.close();

    AySonuDatabase adb=new AySonuDatabase(context);
    adb.open();
    String result[]= new String[25];

**line:49** result = adb.getDataMain(Integer.getInteger(result2[0]), result2[1]);
    adb.close();
    bakici.setText(result[2]);
    arabaKredisi.setText(result[3]);
    ogrenimKredisi.setText(result[4]);
    tatilKredisi.setText(result[5]);
    elektrik.setText(result[6]);
    su.setText(result[7]);
    internet.setText(result[8]);
    aidat.setText(result[9]);
    kasko.setText(result[10]);
    digerTaksitler.setText(result[11]);
    diger.setText(result[12]);
    maasSelo.setText(result[13]);
    maasHilal.setText(result[14]);
    digerGelirler.setText(result[15]);
    toplamHarcama.setText(result[16]);
    toplamGelir.setText(result[17]);
    eldeKalan.setText(result[18]);

    Log.i(TAG, "mainFragmentonCreateView");
    return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}

}

这是数据库类:

public class AySonuDatabase {

public static final String TAG = DatabaseHelper.class.getSimpleName();
public static final String DB_NAME = "butcedb.sql";
private static String DB_PATH ="/data/data/com.bilge.aysonu/assets/";
public static final int DB_VERSION = 1;
public static final String DB_TABLE = "harcamalar";

public static final String C_ID = "c_id";// Special for id
public static final String C_YIL = "spinnerYillar";
public static final String C_AY = "spinnerAylar";
public static final String C_BAKICI = "editTextBakici";
public static final String C_KREDIARABA = "editTextKrediAraba";
public static final String C_KREDIOGRENIM = "editTextKrediOgrenim";
public static final String C_KREDITATIL = "editTextKrediTatil";
public static final String C_FATURAELEKTRIK = "editTextFaturaElektrik";
public static final String C_FATURASU = "editTextFaturaSu";
public static final String C_FATURAINTERNET = "editTextFaturaInternet";
public static final String C_AIDAT = "editTextAidat";
public static final String C_KASKOSIGORTA = "editTextKaskoSigorta";

public static final String C_DIGERTAKSITLER = "editTextDigerTaksitler";
public static final String C_DIGER = "editTextDiger";
public static final String C_MAASSELO = "editTextMaasSelo";
public static final String C_MAASHILAL = "editTextMaasHilal";
public static final String C_DIGERGELIRLER = "editTextDigerGelirler";
public static final String C_TOPLAMHARCAMA = "editTextToplamHarcama";
public static final String C_TOPLAMGELIR = "editTextToplamGelir";
public static final String C_ELDEKALAN = "editTextEldeKalan";

public static final String CREATE_TABLE="CREATE TABLE harcamalar (c_id integer primary key autoincrement," +
        "spinnerYillar integer,spinnerAylar TEXT,editTextBakici integer,editTextKrediAraba integer,editTextKrediOgrenim integer,editTextKrediTatil integer," +
        "editTextFaturaElektrik integer,editTextFaturaSu integer,editTextFaturaInternet integer,editTextAidat integer,editTextKaskoSigorta integer," +
        "editTextDigerTaksitler integer,editTextDiger integer,editTextMaasSelo integer,editTextMaasHilal integer,editTextDigerGelirler integer," +
        "editTextToplamHarcama integer,editTextToplamGelir integer, editTextEldeKalan integer);";

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


public static class DatabaseHelper extends SQLiteOpenHelper {


    public DatabaseHelper(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 AySonuDatabase(Context c) {
    ourContext = c;

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

public  void open() throws NumberFormatException {

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

public void close() {

    dbHelper.close();
    ourDatabase.close();
}
public void Entry(int yilsql, String aysql, int bakicisql,
        int krediArabasql, int krediOgrenimsql, int krediTatilsql,
        int faturaElektriksql, int faturaSusql, int faturaInternetsql,
        int aidatsql, int kaskoSigortasql, int digerTaksitlersql, 
        int digersql, int maasSelosql,int maasHilalsql,int digerGelirlersql,
        int toplamHarcamasql,int toplamGelirsql,int eldeKalansql ) {

    ContentValues cv = new ContentValues();
    cv.put(C_YIL, yilsql);
    cv.put(C_AY, aysql);
    cv.put(C_BAKICI, bakicisql);
    cv.put(C_KREDIARABA, krediArabasql);
    cv.put(C_KREDIOGRENIM, krediOgrenimsql);
    cv.put(C_KREDITATIL, krediTatilsql);
    cv.put(C_FATURAELEKTRIK, faturaElektriksql);
    cv.put(C_FATURASU, faturaSusql);
    cv.put(C_FATURAINTERNET, faturaInternetsql);
    cv.put(C_AIDAT, aidatsql);
    cv.put(C_KASKOSIGORTA, kaskoSigortasql);
    cv.put(C_DIGERTAKSITLER, digerTaksitlersql);
    cv.put(C_DIGER, digersql);
    cv.put(C_MAASSELO,maasSelosql);
    cv.put(C_MAASHILAL, maasHilalsql);
    cv.put(C_DIGERGELIRLER, digerGelirlersql);
    cv.put(C_TOPLAMHARCAMA,toplamHarcamasql);
    cv.put(C_TOPLAMGELIR, toplamGelirsql);
    cv.put(C_ELDEKALAN, eldeKalansql);

    String[] selectionArgs=new String[]{yilsql+"", aysql};
    String entryGirisSQL="SELECT c_id FROM harcamalar WHERE "+C_YIL+"= ? AND "+C_AY+"= ?";
    Cursor cursor=ourDatabase.rawQuery(entryGirisSQL, selectionArgs);
    cursor.moveToFirst();

    int index=cursor.getInt(cursor.getColumnIndex(C_ID));
    if(cursor.isNull(cursor.getColumnIndex(C_ID)))
        ourDatabase.insert(DB_TABLE, null, cv);
    else
        ourDatabase.update(DB_TABLE, cv, C_ID+"="+index, null);

    cursor.close();

}

protected String [] getDataMain(int yilsql,String aysql){         字符串结果[] = new String [25];

    String[] selectionArgs=new String[]{yilsql+"", aysql};
    String entryHesaplaSQL="SELECT * FROM harcamalar WHERE "+C_YIL+"= ? AND "+C_AY+"= ?";
    Cursor c=ourDatabase.rawQuery(entryHesaplaSQL, selectionArgs);

    if(c.moveToFirst()){

        int i_yil = c.getColumnIndex(C_YIL);
        int i_ay = c.getColumnIndex(C_AY);
        int i_bakici = c.getColumnIndex(C_BAKICI);
        int i_krediaraba = c.getColumnIndex(C_KREDIARABA);
        int i_krediogrenim = c.getColumnIndex(C_KREDIOGRENIM);
        int i_kreditatil = c.getColumnIndex(C_KREDITATIL);
        int i_faturaelektrik = c.getColumnIndex(C_FATURAELEKTRIK);
        int i_faturasu = c.getColumnIndex(C_FATURASU);
        int i_faturainternet = c.getColumnIndex(C_FATURAINTERNET);
        int i_aidat = c.getColumnIndex(C_AIDAT);
        int i_kaskosigorta = c.getColumnIndex(C_KASKOSIGORTA);

        int i_digertaksitler=c.getColumnIndex(C_DIGERTAKSITLER);
        int i_diger=c.getColumnIndex(C_DIGER);
        int i_maasselo=c.getColumnIndex(C_MAASSELO);
        int i_maashilal=c.getColumnIndex(C_MAASHILAL);
        int i_digergelirler=c.getColumnIndex(C_DIGERGELIRLER);
        int i_toplamharcama=c.getColumnIndex(C_TOPLAMHARCAMA);
        int i_toplamgelir=c.getColumnIndex(C_TOPLAMGELIR);
        int i_eldekalan=c.getColumnIndex(C_ELDEKALAN);

        result[0]=c.getString(i_yil);
        result[1]=c.getString(i_ay);
        result[2]=c.getString(i_bakici);
        result[3]=c.getString(i_krediaraba);
        result[4]=c.getString(i_krediogrenim);
        result[5]=c.getString(i_kreditatil);
        result[6]=c.getString(i_faturaelektrik);
        result[7]=c.getString(i_faturasu);
        result[8]=c.getString(i_faturainternet);
        result[9]=c.getString(i_aidat);
        result[10]=c.getString(i_kaskosigorta);
        result[11]=c.getString(i_digertaksitler);
        result[12]=c.getString(i_diger);
        result[13]=c.getString(i_maasselo);
        result[14]=c.getString(i_maashilal);
        result[15]=c.getString(i_digergelirler);
        result[16]=c.getString(i_toplamharcama);
        result[17]=c.getString(i_toplamgelir);
        result[18]=c.getString(i_eldekalan);
        c.close();
        return result;
    } else{

        final String string1= "No data!";
        for(int i=2;i<19;i++)
            result[i]=string1;

        return result; 
    }

}

}

这是getData()方法的全部类:

    public class TemporaryDatabase {

public static final String TAG = DbHelperTemporary.class.getSimpleName();
public static final String DB_NAME = "aySonuTepmDB.sql";
private static String DB_PATH ="/data/data/com.bilge.aysonu/assets/";
public static final int DB_VERSION = 1;
public static final String DB_TABLE = "ayyil";

public static final String C_ID = "c_id";// Special for id
public static final String C_YIL = "spinnerYillar";
public static final String C_AY = "spinnerAylar";

public static final String CREATE_TABLE="CREATE TABLE ayyil (c_id integer primary key autoincrement," +
        "spinnerYillar integer,spinnerAylar TEXT);";


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

public static class DbHelperTemporary extends SQLiteOpenHelper {


    public DbHelperTemporary(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 TemporaryDatabase(Context c) {
    ourContext = c;

}

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

public  void open() throws NumberFormatException {


        dbHelper = new DbHelperTemporary(ourContext);
        ourDatabase = dbHelper.getWritableDatabase();
        return ;

}

public void close() {

    dbHelper.close();
    ourDatabase.close();
}

public void Entry(int yilsql, String aysql) {

    ContentValues cv = new ContentValues();
    cv.put(C_YIL, yilsql);
    cv.put(C_AY, aysql);
    ourDatabase.delete(DB_TABLE, null, null);
    ourDatabase.insert(DB_TABLE, null, cv);
    cv.clear();
}

public String[] getData() {

    String[] columns = new String[] { C_YIL, C_AY };
    Cursor c = ourDatabase.query(DB_TABLE, null, null, null, null, null,null);
    String[] result = new String[2];

    int i_yil = c.getColumnIndex(C_YIL);
    int i_ay = c.getColumnIndex(C_AY);

    if (c.moveToFirst()) {
        result[0]=c.getString(i_yil);
        result[1]=c.getString(i_ay);
    }
    c.close();
    return result;

}

}

这是例外:

I/MainFragment(1838): mainFragmentonCreate
D/AndroidRuntime(1838): Shutting down VM
W/dalvikvm(1838): threadid=1: thread exiting with uncaught exception (group=0xb3d87908)
E/AndroidRuntime(1838): FATAL EXCEPTION: main
E/AndroidRuntime(1838): java.lang.NullPointerException
E/AndroidRuntime(1838):     at        com.bilge.aysonu.MainFragment.onCreateView(MainFragment.java:49)
E/AndroidRuntime(1838):atandroid.support.v4.app.Fragment.performCreateView( Fragment.java:1460)
E/AndroidRuntime(1838):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
E/AndroidRuntime(1838):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
E/AndroidRuntime(1838):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
E/AndroidRuntime(1838):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
E/AndroidRuntime(1838):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
E/AndroidRuntime(1838):     at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(1838):     at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(1838):     at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1838):     at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1838):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1838):     at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1838):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1838):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1838):     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

onCreateView可能在生命周期中过早,无法访问数据库 - 我猜你的getActivity()调用返回null。

我将数据库代码移动到onResume()

答案 1 :(得分:0)

好的,显然result2[0]中的值是null但是有太多不清楚的东西。

  1. ourDatabase方法

  2. 中的getData()是什么
  3. ourDatabase是否已正确打开。

  4. 此行c

  5. Cursor c = ourDatabase.query(DB_TABLE, null, null, null, null, null,null);的结果是什么?

    4.为什么你首先初始化result2数组然后分配它 - 只需这样:String[] result2=tdb.getData();

答案 2 :(得分:0)

我发现我做错了。该计划抛出;

    java.lang.NullPointerException 

在第49行

    result = adb.getDataMain(Integer.getInteger(result2[0]), result2[1]);

在这一行ı想要将字符串解析为整数而不是Integer.parseInt()方法我使用了Integer.getInteger()方法。所以代码是;

    result = adb.getDataMain(Integer.parseInt(result2[0]), result2[1]);