将文件从片段保存到SQLite

时间:2014-01-28 08:55:14

标签: android sqlite android-fragments

我使用FragTest和Frag2进行NewContact活动。我正在尝试在FragTest中获取字符串并将其保存在我的数据库中。我的Frag2只是一个空视图。

logcat的

01-28 08:41:37.353: E/AndroidRuntime(1313): FATAL EXCEPTION: main
01-28 08:41:37.353: E/AndroidRuntime(1313): java.lang.NullPointerException
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at com.example.addressbookapp.DBHelper.insertContact(DBHelper.java:67)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at com.example.addressbookapp.FragTest$1.onClick(FragTest.java:46)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.view.View.performClick(View.java:4240)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.view.View$PerformClick.run(View.java:17721)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.os.Handler.handleCallback(Handler.java:730)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.os.Looper.loop(Looper.java:137)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at android.app.ActivityThread.main(ActivityThread.java:5103)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at java.lang.reflect.Method.invokeNative(Native Method)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at java.lang.reflect.Method.invoke(Method.java:525)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-28 08:41:37.353: E/AndroidRuntime(1313):     at dalvik.system.NativeStart.main(Native Method)

NewContact.java

public class NewContact extends FragmentActivity {

    ViewPager viewPager = null;     

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_new_contact);

        viewPager = (ViewPager)findViewById(R.id.pager);    
        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new MyAdapter(fragmentManager));   
        viewPager.setOffscreenPageLimit(2);
    }

    public class MyAdapter extends FragmentStatePagerAdapter {  

            public MyAdapter (FragmentManager fm) {
                super(fm);
            }

            @Override
            public Fragment getItem(int i) {
                Fragment fragment = null;

                if (i == 0)
                {
                    fragment = new FragTest();
                }
                if (i == 1)
                {
                    fragment = new Frag2();
                }
                return fragment;

            }

            @Override
            public int getCount() {
                return 2;
            }   
    }

}

FragTest.java

public class FragTest extends Fragment { 

    EditText first_name, last_name, phone_number, email_address, home_address;
    Button addNewContact;
    DBHelper dbHelper = new DBHelper(getActivity());

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_test, container, false);    

        first_name = (EditText) v.findViewById(R.id.firstName);
        last_name = (EditText) v.findViewById(R.id.lastName);
        phone_number = (EditText) v.findViewById(R.id.phoneNumber);
        email_address = (EditText) v.findViewById(R.id.emailAddress);
        home_address = (EditText) v.findViewById(R.id.homeAddress);

        //save button
        addNewContact = (Button) v.findViewById(R.id.saveButton);
        addNewContact.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                HashMap<String, String> queryValuesMap = new HashMap<String, String>();

                queryValuesMap.put("firstName", first_name.getText().toString());
                queryValuesMap.put("lastName", last_name.getText().toString());
                queryValuesMap.put("phoneNumber", phone_number.getText().toString());
                queryValuesMap.put("emailAddress", email_address.getText().toString());
                queryValuesMap.put("homeAddress", home_address.getText().toString());

                dbHelper.insertContact(queryValuesMap);
            }
        });

        return v;
    }
}

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "my_database.db";
    private static final String TABLE_NAME = "my_table";
    public static final String UID = "_id";
    private static final String FIRST_NAME = "firstName";
    private static final String LAST_NAME = "lastName";
    private static final String PHONE_NUMBER = "phoneNumber";
    private static final String EMAIL_ADDRESS = "emailAddress";
    private static final String HOME_ADDRESS = "homeAddress";

    private Context context;

    // databaseVersion
    private static final int DATABASE_VERSION = 18;

    // database statements
    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
            + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + FIRST_NAME
            + " VARCHAR (255), " + LAST_NAME + " VARCHAR (255), "
            + PHONE_NUMBER + " VARCHAR(255), " + EMAIL_ADDRESS
            + " VARCHAR (255), " + HOME_ADDRESS + " VARCHAR(255));";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS "
            + TABLE_NAME;

    public DBHelper(Context context) {
        // context, database_name, cursorFactory, databaseVersion
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            Message.message(context, "onCreate called");
            db.execSQL(CREATE_TABLE);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            Message.message(context, "ERROR MESSAGE: " + e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            Message.message(context, "onUpgrade called");
            db.execSQL(DROP_TABLE);
            onCreate(db);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            Message.message(context, "ERROR MESSAGE: " + e);
        }
    }

    public void insertContact(HashMap<String, String> queryValues) {
        SQLiteDatabase sqdb = this.getWritableDatabase();
        ContentValues ct_v = new ContentValues();

        ct_v.put("firstName", queryValues.get("firstName"));
        ct_v.put("lastName", queryValues.get("lastName"));
        ct_v.put("phoneNumber", queryValues.get("phoneNumber"));
        ct_v.put("emailAddress", queryValues.get("emailAddress"));
        ct_v.put("homeAddress", queryValues.get("homeAddress"));

        sqdb.insert(TABLE_NAME, null, ct_v);
        sqdb.close();
    }

    public int updateContact(HashMap<String, String> queryValues) {
        SQLiteDatabase sqdb = this.getWritableDatabase();
        ContentValues ct_v = new ContentValues();

        // update(contentValues): name of column, new value
        ct_v.put("firstName", queryValues.get("firstName"));
        ct_v.put("lastName", queryValues.get("lastName"));
        ct_v.put("phoneNumber", queryValues.get("phoneNumber"));
        ct_v.put("emailAddress", queryValues.get("emailAddress"));
        ct_v.put("homeAddress", queryValues.get("homeAddress"));

        return sqdb.update(TABLE_NAME, ct_v, UID + " =? ",
                new String[] { queryValues.get("unique_id") });
    }

    public void deleteContact(String id) {
        SQLiteDatabase sqdb = this.getWritableDatabase();
        String deleteQuery = "DELETE FROM " + TABLE_NAME + " WHERE " + UID
                + " = '"+id+"';";
        sqdb.execSQL(deleteQuery);
    }

    public ArrayList<HashMap<String, String>> getAllContacts() {
        // contains every row of the database
        ArrayList<HashMap<String, String>> contactArrayList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT * FROM "+TABLE_NAME+" ORDER BY "+LAST_NAME+";";

        SQLiteDatabase sqdb = this.getWritableDatabase();

        Cursor cursor = sqdb.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {

            do {
                HashMap<String, String> contactMap = new HashMap<String, String>();

                contactMap.put("unique_id", cursor.getString(0));
                contactMap.put("firstName", cursor.getString(1));
                contactMap.put("lastName", cursor.getString(2));
                contactMap.put("phoneNumber", cursor.getString(3));
                contactMap.put("emailAddress", cursor.getString(4));
                contactMap.put("homeAddress", cursor.getString(5));

                contactArrayList.add(contactMap);
            } while (cursor.moveToNext());
        }
        return contactArrayList;
    }

    public HashMap<String, String> getContactInfo(String id) {

        HashMap<String, String> contactMap = new HashMap<String, String>();
        SQLiteDatabase sqdb = this.getReadableDatabase();

        String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + UID
                + "= '"+id+"';";

        Cursor cursor = sqdb.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {

            do {

                contactMap.put("unique_id", cursor.getString(0));
                contactMap.put("firstName", cursor.getString(1));
                contactMap.put("lastName", cursor.getString(2));
                contactMap.put("phoneNumber", cursor.getString(3));
                contactMap.put("emailAddress", cursor.getString(4));
                contactMap.put("homeAddress", cursor.getString(5));

            } while (cursor.moveToNext());

        }
        return contactMap;
    }
}

2 个答案:

答案 0 :(得分:3)

替换

DBHelper dbHelper = new DBHelper(getActivity()); 

DBHelper dbHelper = null; 

并将其初始化为onCreateView

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_test, container, false);

        dbHelper = new DBHelper(getActivity()); // HERE IT IS
        .....
  }

答案 1 :(得分:1)

您过早构建DBHelper。此处传递的getActivity() Contextnull

DBHelper dbHelper = new DBHelper(getActivity());

将初始化推迟到例如片段附加到活动的onCreateView()