当我用Tabs滚动PagerView时,Android NullPointerException

时间:2016-03-03 20:33:32

标签: android database android-fragments nullpointerexception

我在另一个应用程序中使用相同的代码,它工作正常,我不明白为什么在这里我收到NullPointerException。 这是我与Fragments的第一次,也许我写错了! 代码下方。

这是我的Thrd Fragment

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;


public class ThreeFragment extends Fragment {

    public  MySQLiteHelper db = new MySQLiteHelper(getContext());
    public List<VotiEsami> esami;
    public VotiEsamiAdapter adapter; //Adapter per caricare la listview di voti

    public ThreeFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_three, container, false);

        //Find the listview
        final ListView listView = (ListView)view.findViewById(R.id.voti_listView);

        //Get all exams inside database
        esami = db.getVotiEsami();
        adapter = new VotiEsamiAdapter(getContext(), R.layout.listview_voti_line, null);

        listView.setAdapter(adapter);

        //TODO gestire cancellazione del voto dal DB e dalla listview




        Button nuovo_voto = (Button) view.findViewById(R.id.button_add_new_voto);
        nuovo_voto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //Start Dialog for input the new vote
                Intent myIntent = new Intent(getActivity(), DialogAddVotoEsame.class);
                ThreeFragment.this.startActivityForResult(myIntent, 1);

            }
        });



        return view;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {

                String result_nome = data.getStringExtra("result_name_esame"); //Take the materia from Dialog
                int result_cfu = data.getIntExtra("result_cfu_esame", 1); //Take the materia from Dialog
                int result_voto = data.getIntExtra("result_voto_esame", 1); //Take the materia from Dialog

                //Add exam with vote to DB
                db.addEsameVoto(new VotiEsami(result_nome, result_cfu, result_voto));

                //Refresh list
                List<VotiEsami> newesame = db.getVotiEsami();

                //Aggiorno la Listview dell'activity con il nuovo inserimento
                esami.clear();
                esami.addAll(newesame);
                adapter.notifyDataSetChanged();

            }

        }
    }//onActivityResult

}

在这里,我有如何管理数据库

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


import java.util.ArrayList;
import java.util.List;

public class MySQLiteHelper extends SQLiteOpenHelper {

    //Database version
    private static final int DATABASE_VERSION = 1;

    //Database name
    private static final String DATABASE_NAME = "agendaDB";

    //Materie table name
    public static final String TABLE_VOTI_ESAMI = "esami";

    //Table_voti_esami columns
    public static final String COLUMN_NOME_ESAME = "nome_esame";
    public static final String COLUMN_CFU_ESAME = "cfu_esame";
    public static final String COLUMN_VOTO_ESAME = "voto_esame";


    //Stringa di creazione tabelle per database
    //Tabella voti esami
    private static final String CREATE_VOTO_ESAME_TABLE = "CREATE TABLE "
            + TABLE_VOTI_ESAMI + "("
            + COLUMN_NOME_ESAME + " TEXT,"
            + COLUMN_CFU_ESAME + " INTEGER,"
            + COLUMN_VOTO_ESAME + " INTEGER" + ")";



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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_VOTO_ESAME_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_VOTI_ESAMI);

        // Create tables again
        onCreate(db);
    }

    //Restituisco tutti gli esami dati
    public List<VotiEsami> getVotiEsami(){

        List<VotiEsami> esamiList = new ArrayList<>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_VOTI_ESAMI;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if(cursor != null) {
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    VotiEsami esami = new VotiEsami();
                    esami.set_nome_esame(cursor.getString(0));
                    esami.set_cfu(Integer.parseInt(cursor.getString(1)));
                    esami.set_voto(Integer.parseInt(cursor.getString(2)));

                    // Adding materia activity voti to list
                    esamiList.add(esami);
                } while (cursor.moveToNext());
            }
        }else{
            return null;
        }
        // return contact list
        return esamiList;

    }

    // Aggiunta nuova materia sull activity voti
    public void addEsameVoto(VotiEsami esam) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(COLUMN_NOME_ESAME, esam.get_nome_esame());
        values.put(COLUMN_CFU_ESAME, esam.get_cfu());
        values.put(COLUMN_VOTO_ESAME, esam.get_voto());

        // Inserting Row
        db.insert(TABLE_VOTI_ESAMI, null, values);
        db.close(); // Closing database connection
    }

}//Chiudo classe

使用相同的数据库,相同的方法在另一个应用程序中使用NullPointerException而无效{简单Activity s)

另一个谜(对我来说): 我有5 Fragment s,对于First,没问题我能看到它,但是如果我去其他人(2,3,4或5)我会得到同样的错误,你可以看到记录它总是写:

E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.application.ddz.agendauniversitaria.MySQLiteHelper.getVotiEsami(MySQLiteHelper.java:70)
at com.application.ddz.agendauniversitaria.ThreeFragment.onCreateView(ThreeFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

有人能告诉我史诗失败在哪里吗? 感谢。

1 个答案:

答案 0 :(得分:0)

我认为您可能需要在db方法中初始化onCreate()对象。

onCreate() 
  

系统在创建片段时调用此方法。内   你的实现,你应该初始化的基本组件   片段暂停时要保留的片段   停了,然后又恢复了。

所以你可以这样做:

public class ThreeFragment extends Fragment {

    public  MySQLiteHelper db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = new MySQLiteHelper(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Your code
        esami = db.getVotiEsami();
    }
}