getWritableDatabase()中的空指针异常?

时间:2016-02-04 15:21:22

标签: android sqlite nullpointerexception

我是android开发和sqlite的新手。当我尝试将对象插入数据库时​​,它会在getWritabledatabase()中抛出空指针异常。我不知道我在哪里弄错了。这是我的代码:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

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

public class Task_DB {
    SQLiteDatabase sqLiteDatabase;
    private Database_SF_APP dbHelper;

Context context;

public Task_DB(Context context){
    dbHelper=new Database_SF_APP(context);
}
    public void insert(Model_Task_List student) {

        //Open connection to write data
Database_SF_APP dbHelper=new Database_SF_APP(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Model_Task_List.KEY_username, student.getUserName());
        values.put(Model_Task_List.KEY_subject,student.getSubject());
        values.put(Model_Task_List.KEY_task, student.getTaskStatus());

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



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


    public void delete(int student_Id) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // It's a good practice to use parameter ?, instead of concatenate string
        db.delete(Model_Task_List.KEY_table, Model_Task_List.KEY_id + "= ?", new String[] { String.valueOf(student_Id) });
        db.close(); // Closing database connection
    }

    public void update(Model_Task_List student) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(Model_Task_List.KEY_username, student.getUserName());
        values.put(Model_Task_List.KEY_subject,student.getSubject());
        values.put(Model_Task_List.KEY_task, student.getTaskStatus());

        // It's a good practice to use parameter ?, instead of concatenate string
        db.update(Model_Task_List.KEY_table, values,Model_Task_List.KEY_id + "= ?", new String[] { String.valueOf(student.getId()) });
        db.close(); // Closing database connection
    }

    public List<Model_Task_List> getStudentList() {
        //Open connection to read only

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  " +
                Model_Task_List.KEY_id + "," +
                Model_Task_List.KEY_username + "," +
                Model_Task_List.KEY_subject + "," +
                Model_Task_List.KEY_task +
                " FROM " + Model_Task_List.KEY_table;

        //Student student = new Student();
        List<Model_Task_List>listobj=new ArrayList<Model_Task_List>();

        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list

        if (cursor.moveToFirst()) {
            while (cursor.moveToNext()) {
                Model_Task_List modelobj=new Model_Task_List();
                modelobj.setId(Integer.parseInt(cursor.getString(0)));
                modelobj.setUserName(cursor.getString(1));
                modelobj.setSubject(cursor.getString(2));
                modelobj.setTaskStatus(cursor.getString(3));
                listobj.add(modelobj);

            }
        }      
        return listobj;    
    }
}

这是数据库助手类:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Database_SF_APP  extends SQLiteOpenHelper {
    //version number to upgrade database version
    //each time if you Add, Edit table, you need to change the
    //version number.
    Context context;
    private static final int DATABASE_VERSION = 4;

    // Database Name
    private static final String DATABASE_NAME = "crud.db";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        //All necessary tables you like to create will create here

        String CREATE_TABLE_STUDENT = "CREATE TABLE " + Model_Task_List.KEY_table  + "("
                + Model_Task_List.KEY_id  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + Model_Task_List.KEY_username + " TEXT, "
                + Model_Task_List.KEY_subject + " TEXT, "
                + Model_Task_List.KEY_task + " TEXT )";

        db.execSQL(CREATE_TABLE_STUDENT);    
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed, all data will be gone!!!
        db.execSQL("DROP TABLE IF EXISTS " + Model_Task_List.KEY_table);

        // Create tables again
        onCreate(db);    
    }

}

这是我插入数据库的片段:

public class Task extends Fragment  {
    private static final String MY_PREFERENCE_KEY = "yogan";
    private List<Model_Task_List> model_task_lists;

    //Creating Views
    String currentDateTimeString;
    Context context;
    SharedPreferences.Editor editor;
    private RecyclerView recyclerView;
    Task_List_Adapter taskadapter;
    private RecyclerView.LayoutManager layoutManager;
    SharedPreferences sharedPreferences;
    private RecyclerView.Adapter adapter;
    RequestQueue yog;
    Task_DB taskobj = new Task_DB(getContext());
    String yogan;
    AppController app;
    RequestQueue queue;
    String Url;
    Task_DB task_db=new Task_DB(getActivity());
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_task, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        if (model_task_lists == null) {
            model_task_lists = new ArrayList<Model_Task_List>();
        }
        recyclerView.setLayoutManager(layoutManager);
 /*    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        if(sharedPreferences.contains("yogan")) {
            editor = sharedPreferences.edit();
            editor.putBoolean("yog", true);
            String jsons = sharedPreferences.getString(MY_PREFERENCE_KEY, "");

            Gson gsong = new Gson();

            Type type = new TypeToken<ArrayList<Model_Task_List>>() {
            }.getType();
            model_task_lists = gsong.fromJson(jsons, type);
*/
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
            recyclerView.setAdapter(taskadapter);


        ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
         {
            Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
             /*   SharedPreferences shared=getPreferenceManager().getDefaultSharedPreferences(getActivity().getBaseContext());
                String yog=shared.getString("example_text","");
              if(yog!=null){
               Intent intent=new Intent(getActivity(),LoginActivity.class);
                startActivity(intent);
                }*/

     SharedPreferences sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
        yogan = sharedPreferences.getString("user_id", null);
       queue= Volley.newRequestQueue(getContext());
        Url = "http://xxx.xx.xx.x/xxxs/GetActivitiesByUserID.svc/getlist/GetTask/864" ;
        //Creating a json array request

            JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.GET, Url, new JSONObject(),
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            String server_response = response.toString();
                            try {
                                JSONObject json_object = new JSONObject(server_response);
                                JSONArray json_array = new JSONArray(json_object.getString("GetTaskResult"));
                                for (int i = 0; i < json_array.length(); i++) {
                                    Model_Task_List modelobj = new Model_Task_List();

                                    JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
                                    modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
                                    modelobj.setUserName(json_arrayJSONObject.getString("UserName"));
                                    modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus")) ;
                                    model_task_lists.add(modelobj);

                                    task_db.insert(modelobj);
                                }   

                                //Finally initializing our adapter


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
                            Log.e("yog", error.toString());
                        }
                    });

            //Creating request queue

            queue.add(jsonArrayRequest);


        }


        return view;
    }


    @Override
    public void onResume() {

        super.onResume();
    }


    @Override
    public void onStop() {
        //queue.stop();
       /* SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
        editor = sharedpref.edit();
        Gson gson = new Gson();
        String god = gson.toJson(model_task_lists);
        editor.putBoolean("yogan", true);
        editor.putString(MY_PREFERENCE_KEY, god);
        editor.commit();
*/
 super.onStop();
    }


}

这是我的logcat:

 ntime: FATAL EXCEPTION: main

 java.lang.NullPointerException
 at xx.xx.Task_DB.insert(Task_DB.java:27)
 at xxx.xxx.Task$1.onResponse(Task.java:128)
 at pxx.xxx.Task$1.onResponse(Task.java:111)
 at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
 at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
 at android.os.Handler.handleCallback(Handler.java:733)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:136)
 at android.app.ActivityThread.main(ActivityThread.java:5113)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
 at dalvik.system.NativeStart.main(Native Method)

当我尝试插入时,它会抛出空指针异常。

1 个答案:

答案 0 :(得分:0)

您的context成员变量未初始化,但您正在将其提供给SQLiteOpenHelper构造函数,如下所示:

Database_SF_APP dbHelper=new Database_SF_APP(context);

与许多其他API相反,上下文仅在您调用时使用,例如帮助者getWritableDatabase()