将数据库另存为CSV文件

时间:2018-05-29 21:31:37

标签: android database sqlite csv

我是新的。当用户通过测试时,我得到了一个有4个考试的应用程序。用户的姓名和带有跟踪代码的考试日期和答案将保存在数据库中。在另一方面,用户可以看到已经保存在数据库中的考试结果,我有一个列表视图,显示来自数据库的数据(SQlite数据库)所以我有一个Button,当用户点击它时,它应该将数据库保存为CSV文件。我已经在项目中导入了OPENCSV库。所以我在我的BUTTON中编写代码。但在运行时,我点击按钮。什么都没发生过。在logcat我得到错误:

  

05-29 21:17:43.198 2531-2531 / ir.arbn.www.mytestprogramsamanik E / ResultActivity:尝试调用虚拟方法' android.database.sqlite.SQLiteDatabase ir.arbn.www.mytestprogramsamanik。 DatabaseHelper.getReadableDatabase()'在null对象引用上       java.lang.NullPointerException:尝试调用虚方法' android.database.sqlite.SQLiteDatabase ir.arbn.www.mytestprogramsamanik.DatabaseHelper.getReadableDatabase()'在空对象引用上

数据库类:

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "person.db";
public static final int VERSION = 1;
public static final String TABLE_NAME = "tbl_person";
public static final String S_ID = "id";
public static final String S_NAME = "name";
public static final String S_DATE = "date";
public static final String S_TRACK = "track";
public static final String S_ANSWER = "answer";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "" + "(" + S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + S_NAME + " TEXT NOT NULL," + S_DATE + " TEXT NOT NULL," + S_TRACK + " TEXT NOT NULL," + S_ANSWER + " TEXT NOT NULL)";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, VERSION);
}

public void insertPerson(String name, String date, String track, String answer) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(S_NAME, name);
    contentValues.put(S_DATE, date);
    contentValues.put(S_TRACK, track);
    contentValues.put(S_ANSWER, answer);
    SQLiteDatabase db = this.getWritableDatabase();
    db.insert(TABLE_NAME, null, contentValues);
    db.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)      {
    db.execSQL("DROP TABLE" + TABLE_NAME);
    onCreate(db);
}

public ArrayList<PersonModel> getAllPersonData() {
    ArrayList<PersonModel> list = new ArrayList<>();
    String sql = "SELECT * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.moveToFirst()) {
        do {
            PersonModel pm = new PersonModel();
            pm.setId(cursor.getInt(0) + "");
            pm.setName(cursor.getString(1));
            pm.setDate(cursor.getString(2));
            pm.setTrack(cursor.getString(3));
            pm.setAnswer(cursor.getString(4));
            list.add(pm);
        } while (cursor.moveToNext());
    }
    return list;
}
}

即使在这里你也可以看到活动,我有Listview和保存按钮:

public class ResultActivity extends AppCompatActivity {
@BindView(R.id.listView)
ListView listView;
@BindView(R.id.save)
CustomButton save;
CustomAdapter customAdapter;
ArrayList<PersonModel> arrayList;
DatabaseHelper db;
DatabaseHelper dbhelper;
Context mContext = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    ButterKnife.bind(this);
    db = new DatabaseHelper(this);
    arrayList = new ArrayList<>();
    arrayList = db.getAllPersonData();
    customAdapter = new CustomAdapter(this, arrayList);
    listView.setAdapter(customAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(mContext, FragmentActivity.class);
            startActivity(intent);
        }
    });
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           DatabaseHelper db = new DatabaseHelper(getApplicationContext());
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }
            File file = new File(exportDir, "csvname.csv");
            try {
                file.createNewFile();
                    CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                SQLiteDatabase myDb = dbhelper.getReadableDatabase();
                Cursor curCSV = myDb.rawQuery("SELECT * FROM tbl_person", null);
                csvWrite.writeNext(curCSV.getColumnNames());
                while (curCSV.moveToNext()) {
                    String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2)};
                    csvWrite.writeNext(arrStr);
                }
                csvWrite.close();
                curCSV.close();
            } catch (Exception sqlEx) {
                Log.e("ResultActivity", sqlEx.getMessage(), sqlEx);
            }
        }
    });
}
}

1 个答案:

答案 0 :(得分:2)

您的变量名称似乎犯了错误: 您实例化对象db

 DatabaseHelper db = new DatabaseHelper(getApplicationContext());

但您使用

下方的dbhelper
SQLiteDatabase myDb = dbhelper.getReadableDatabase();

未初始化,并抛出NullPointer。

将上述行更改为SQLiteDatabase myDb = db.getReadableDatabase();