当我尝试在ConfirmPage上查看SQLiteDatabase的数据时,应用崩溃。
MainActivity:
DatabaseHelper myDb;
EditText editTeamOne, editTeamTwo, editLocation, editEmail;
Spinner editSport;
EditText editDate, editTime;
Button btnAddData, btnViewData;
private EditText TeamOne;
private EditText TeamTwo;
private TextView DateOne;
private TextView TimeOne;
private Spinner SportOne;
private EditText LocationOne;
private EditText EmailOne;
private Context context;
private Object view;
private EditText Team1;
private EditText Team2;
private Button btnSubmit;
private TextView Date1;
private TextView Time1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
TeamOne = (EditText) findViewById(R.id.editText);
TeamTwo = (EditText) findViewById(R.id.editText2);
DateOne = (TextView) findViewById(R.id.textView);
TimeOne = (TextView) findViewById(R.id.textView6);
SportOne = (Spinner) findViewById(R.id.spinner1);
LocationOne = (EditText) findViewById(R.id.editText3);
EmailOne = (EditText) findViewById(R.id.editText4);
//button code to go to confirmation page
btnSubmit = (Button) findViewById(R.id.ConfirmButton);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//OnClick of submit Team1 is required and cannot be empty
Team1 = (EditText) findViewById(R.id.editText);
if (TextUtils.isEmpty(Team1.getText())) {
Team1.setError("Team name was not entered");
}
//OnClick of submit where Team2 is required and cannot be empty
Team2 = (EditText) findViewById(R.id.editText2);
if (TextUtils.isEmpty(Team2.getText())){
Team2.setError("Team name was not entered");
}
//OnClick of Submit where Date is required and cannot be empty
Date1 = (TextView) findViewById(R.id.textView);
if (TextUtils.isEmpty(Date1.getText())){
Date1.setError("Date was not selected");
}
Time1 = (TextView) findViewById(R.id.textView6);
if (TextUtils.isEmpty(Time1.getText())){
Time1.setError("Time was not selected");
}
else {
openConfirmPage();
handleButtonClick();
}
}
});
//Date button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
//Time Button
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
//Drop down menu
Spinner spinner = findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sports, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void display(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(currentDateString);
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textView = (TextView) findViewById(R.id.textView6);
textView.setText(hourOfDay + ":" + minute);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void handleButtonClick() {
String strNAME = TeamOne.getText().toString();
String strNAME2 = TeamTwo.getText().toString();
String strNAME3 = DateOne.getText().toString();
String strNAME4 = TimeOne.getText().toString();
String strNAME5 = SportOne.getSelectedItem().toString();
String strNAME6 = LocationOne.getText().toString();
String strName7 = EmailOne.getText().toString();
Intent i = new Intent(this, ConfirmationPage.class);
i.putExtra(ConfirmationPage.NAME, strNAME);
i.putExtra(ConfirmationPage.NAME2, strNAME2);
i.putExtra(ConfirmationPage.Date1, strNAME3);
i.putExtra(ConfirmationPage.Time1, strNAME4);
i.putExtra(ConfirmationPage.Sport1, strNAME5);
i.putExtra(ConfirmationPage.Location1, strNAME6);
i.putExtra(ConfirmationPage.Email1, strName7);
startActivity(i);
}
public void openConfirmPage() {
Intent intentCP = new Intent(this, ConfirmationPage.class);
startActivity(intentCP);
}
确认页面:
公共类ConfirmationPage扩展了AppCompatActivity {
private TextView TeamOne;
private TextView TeamTwo;
private TextView DateOne;
private TextView TimeOne;
private TextView SportOne;
private TextView LocationOne;
private TextView EmailOne;
public static final String NAME = "team_one";
public static final String NAME2 = "team_two";
public static final String Date1 = "date";
public static final String Time1 = "time";
public static final String Sport1 = "sport";
public static final String Location1 = "location";
public static final String Email1 = "email";
DatabaseHelper myDb = new DatabaseHelper(this);
Button btnViewData, btnAddData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation_page);
DatabaseHelper myDb = new DatabaseHelper(this);
btnViewData = (Button)findViewById(R.id.button7);
TeamOne = (TextView) findViewById(R.id.textView3);
TeamTwo = (TextView) findViewById(R.id.textView7);
DateOne = (TextView) findViewById(R.id.textView12);
TimeOne = (TextView) findViewById(R.id.textView13);
SportOne = (TextView) findViewById(R.id.textView14);
LocationOne = (TextView) findViewById(R.id.textView15);
EmailOne = (TextView) findViewById(R.id.textView16);
btnAddData = (Button)findViewById(R.id.button5);
btnViewData = (Button)findViewById(R.id.button7);
TextView teamOne = (TextView)findViewById(R.id.textView3);
TextView teamTwo = (TextView) findViewById(R.id.textView7);
TextView dateOne = (TextView)findViewById(R.id.textView12);
TextView timeOne = (TextView)findViewById(R.id.textView13);
TextView sportOne = (TextView)findViewById(R.id.textView14);
TextView locationOne = (TextView)findViewById(R.id.textView15);
TextView emailOne = (TextView)findViewById(R.id.textView16);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String editText = extras.getString(NAME);
String editText2 = extras.getString(NAME2);
String textView = extras.getString(Date1);
String textView6 = extras.getString(Time1);
String spinner1 = extras.getString(Sport1);
String editText3 = extras.getString(Location1);
String editText4 = extras.getString(Email1);
//If entry is not null set the text to matching id from MainActivity
if (editText != null){
teamOne.setText(editText);
teamTwo.setText(editText2);
dateOne.setText(textView);
timeOne.setText(textView6);
sportOne.setText(spinner1);
locationOne.setText(editText3);
emailOne.setText(editText4);
}
}
btnViewData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openMatchDataPage();
}
});
//ViewData();
AddData();
};
public void AddData() {
btnAddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String date = DateOne.getText().toString();
String time = TimeOne.getText().toString();
String sport = SportOne.getText().toString();
String team_one = TeamOne.getText().toString();
String team_two = TeamTwo.getText().toString();
String location = LocationOne.getText().toString();
String email = EmailOne.getText().toString();
int t1_score = 0;
int t2_score = 0;
boolean insertData = myDb.addData(date, time, sport, team_one, team_two, location, email, t1_score, t2_score);
if (insertData == true) {
Toast.makeText(ConfirmationPage.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ConfirmationPage.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
});
}
public void ViewData() {
btnViewData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor data = myDb.showData();
if (data.getCount() == 0) {
display("Error", "No Data Found.");
return;
}
//display message
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()) {
buffer.append("ID: " + data.getString(0) + "\n");
buffer.append("Date: " + data.getString(1) + "\n");
buffer.append("Time: " + data.getString(2) + "\n");
buffer.append("Sport: " + data.getString(3) + "\n");
buffer.append("Team One: " + data.getString(4) + "\n");
buffer.append("Team Two: " + data.getString(5) + "\n");
buffer.append("Location: " + data.getString(6) + "\n");
buffer.append("Email: " + data.getString(7) + "\n");
buffer.append("Team One Score: " + data.getString(8) + "\n");
buffer.append("Team Two Score: " + data.getString(9) + "\n");
}
display("All Stored Data:", buffer.toString());
}
});
}
public void display(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void openMatchDataPage() {
Intent intentCP = new Intent(this, MatchData.class);
startActivity(intentCP);
}
}
DatabaseHelper:
公共类DatabaseHelper扩展了SQLiteOpenHelper {
public static final String DATABASE_NAME = "match.db";
public static final String TABLE_NAME = "match_table";
public static final String COL1 = "ID";
public static final String COL2 = "DATE";
public static final String COL3 = "TIME";
public static final String COL4 = "SPORT";
public static final String COL5 = "TEAM_ONE";
public static final String COL6 = "TEAM_TWO";
public static final String COL7 = "LOCATION";
public static final String COL8 = "EMAIL";
public static final String COL9 = "T1_SCORE";
public static final String COL10 = "T2_SCORE";
private SQLiteDatabase myDb;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
//myDb = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"DATE TEXT, TIME TEXT, SPORT TEXT, TEAM_ONE TEXT, TEAM_TWO TEXT, LOCATION TEXT, EMAIL TEXT, T1_SCORE TEXT, T2_SCORE TEXT)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String date, String time, String sport, String team_one,
String team_two, String location, String email, int t1_score, int t2_score){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, date);
contentValues.put(COL3, time);
contentValues.put(COL4, sport);
contentValues.put(COL5, team_one);
contentValues.put(COL6, team_two);
contentValues.put(COL7, location);
contentValues.put(COL8, email);
contentValues.put(COL9, t1_score);
contentValues.put(COL10, t2_score);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
public String getDetails() {
Cursor results = myDb.query("match_table",
new String[] {"ID", "DATE", "TIME", "SPORT", "TEAMONE", "TEAMTWO", "LOCATION", "EMAIL", "T1_SCORE", "T2_SCORE"},
null, null, null, null, "ID");
String resultText = "";
results.moveToFirst();
while (!results.isAfterLast()) {
int id = results.getInt(0);
String date = results.getString(1);
String time = results.getString(2);
String sport = results.getString(3);
String team_one = results.getString(4);
String team_two = results.getString(5);
String location = results.getString(6);
String email = results.getString(7);
String t1_score = results.getString(8);
String t2_score = results.getString(9);
resultText += id + " " + date + " " + time + " " + sport + " " + team_one + " " + team_two + " " + location + " " + email + " " + t1_score + " " + t2_score + "\n";
results.moveToNext();
}
return resultText;
}
public boolean updateScore(String id, int t1_score, int t2_score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, id);
contentValues.put(COL9, t1_score);
contentValues.put(COL10, t2_score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return true;
}
public boolean updateData(String id, String date, String time, String sport, String team_one,
String team_two, String location, String email, int t1_score, int t2_score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, id);
contentValues.put(COL2, date);
contentValues.put(COL3, time);
contentValues.put(COL4, sport);
contentValues.put(COL5, team_one);
contentValues.put(COL6, team_two);
contentValues.put(COL7, location);
contentValues.put(COL8, email);
contentValues.put(COL9, t1_score);
contentValues.put(COL10, t2_score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return true;
}
}
MatchData:
公共类MatchData扩展了AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_data);
DatabaseHelper db = new DatabaseHelper(this);
String details = db.getDetails();
TextView detailsTxt = findViewById(R.id.detailsText);
detailsTxt.setText(details);
}
}
2019-12-06 16:44:25.289 19399-19399 / com.example.cwapp E / AndroidRuntime:FATAL EXCEPTION:main 流程:com.example.cwapp,PID:19399 java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.cwapp / com.example.cwapp.MatchData}:java.lang.NullPointerException:尝试调用虚拟方法'android.database.Cursor android.database.sqlite。 SQLiteDatabase.query(java.lang.String,java.lang.String [],java.lang.String,java.lang.String [],java.lang.String,java.lang.String,java.lang.String) '在空对象引用上 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1808) 在android.os.Handler.dispatchMessage(Handler.java:106) 在android.os.Looper.loop(Looper.java:193) 在android.app.ActivityThread.main(ActivityThread.java:6669) 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 原因:java.lang.NullPointerException:尝试调用虚拟方法'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String,java.lang.String [],java.lang.String, null对象引用上的java.lang.String [],java.lang.String,java.lang.String,java.lang.String) 在com.example.cwapp.DatabaseHelper.getDetails(DatabaseHelper.java:79) 在com.example.cwapp.MatchData.onCreate(MatchData.java:17) 在android.app.Activity.performCreate(Activity.java:7136) 在android.app.Activity.performCreate(Activity.java:7127) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1808) 在android.os.Handler.dispatchMessage(Handler.java:106) 在android.os.Looper.loop(Looper.java:193) 在android.app.ActivityThread.main(ActivityThread.java:6669) 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
答案 0 :(得分:0)
您可以通过注释禁用myDb
的初始化。
要么启用它
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
myDb = getWritableDatabase();
}
或在getWritableDatabase()
内添加getDetails()
public String getDetails() {
//Add this
SQLiteDatabase myDb = this.getWritableDatabase();
...
}