-1

Im new. I got an application that has 4 exam, when user pass the tests. user's name and the date of exam with a tracking code and the answer will be save in database. In other side, user can see the result of exam, which already saved in database and I have a listview that show data from database (SQlite database) so i got a Button, when user click on it, it should save the database as CSV file. I already imported the OPENCSV library in my project. so i write the code in my BUTTON. but at run, when i click on button. nothing gonno happen. and in logcat i get error:

05-29 21:17:43.198 2531-2531/ir.arbn.www.mytestprogramsamanik E/ResultActivity: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase ir.arbn.www.mytestprogramsamanik.DatabaseHelper.getReadableDatabase()' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase ir.arbn.www.mytestprogramsamanik.DatabaseHelper.getReadableDatabase()' on a null object reference


the Database Class:

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;
}
}

even here you can see the Activity with i have the Listview and the save button:

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);
            }
        }
    });
}
}
A.R.B.N
  • 1,035
  • 2
  • 10
  • 20
  • Do you use `dbHelper` without initializing it ? – Arthur Attout May 29 '18 at 21:32
  • i guess i've already done it. – A.R.B.N May 29 '18 at 21:34
  • Im wondering why people gave negative point to my post... – A.R.B.N Jun 02 '18 at 14:48
  • Because this is an error you could have figured out by yourself. NullPointerExceptions are Java 101, and when you stumble upon them, you should invesigate. I honestly doubt you have been searching a lot for your mistake before posting it on S.O. – Arthur Attout Jun 03 '18 at 12:21
  • When someone post the problem, that mean he/she already searched for problem. And this place is somewhere we can ask our question and get helped. For the problem. And it doesn't matter what problem is. – A.R.B.N Jun 03 '18 at 12:32
  • Yes, this is a place where you ask questions and get helped, but this is not a classroom. You got downvotes because your question is equivalent to ["What is a NullPointerException and how do I fix it ?"](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). Yes, it does matter what the problem is. And also, try to avoid using he/she pronouns. Prefer "they". – Arthur Attout Jun 03 '18 at 12:55

1 Answers1

2

You seem to have made a mistake with your variable names : You instantiate your object db

 DatabaseHelper db = new DatabaseHelper(getApplicationContext());

But you use dbhelper just below

SQLiteDatabase myDb = dbhelper.getReadableDatabase();

Which is not initialized, and throws a NullPointer.

Change the above line to SQLiteDatabase myDb = db.getReadableDatabase();

Arthur Attout
  • 2,701
  • 2
  • 26
  • 49
  • thanks. you make me favore :-). but i got one probleb. when i click on button. file will be save on root. how can i save it in Download Path or somewhere user want – A.R.B.N May 29 '18 at 21:45
  • Well, this is a completely different question, and I'll have to refer to [this post](https://stackoverflow.com/a/28404125/7540393) to give you an answer – Arthur Attout May 29 '18 at 21:52