我已经有这个问题了一段时间了。由于某种原因,它将它添加到数据库,但它会出现此错误并导致程序崩溃。
java.lang.NullPointerException:尝试调用虚拟方法'long com.example.munaj.feedmeg.DataBaseHelper.insertRow(java.lang.String,java.lang.String,java.lang.String,java.lang。对象引用上的String,java.lang.String,java.lang.String,java.lang.String)'
有很多随机填充,但我找到了我的错误。
这是我的数据库文件
public class DataBaseHelper extends SQLiteOpenHelper{
private static final String TAG = "DBAdapter"; // used for logging database version
//Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_START_TIME = "sTime";
public static final String KEY_FINISH_TIME = "fTime";
public static final String KEY_LOC = "loc";
public static final String KEY_ROOM = "room";
public static final String KEY_DES = "des";
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TASK, KEY_DATE,KEY_START_TIME, KEY_FINISH_TIME, KEY_LOC, KEY_ROOM, KEY_DES};
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
public static final int COL_FTIME = 3;
//Column Numbers for each Field Name:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 5;
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TASK + " TEXT NOT NULL, "
+ KEY_DATE + " TEXT, "
+ KEY_START_TIME + " TEXT NOT NULL,"
+ KEY_FINISH_TIME + " TEXT NOT NULL,"
+ KEY_LOC + " TEXT NOT NULL,"
+ KEY_ROOM + " TEXT NOT NULL,"
+ KEY_DES + " TEXT NOT NULL"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DataBaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
//Open the database connection
public DataBaseHelper open(){
db = myDBHelper.getWritableDatabase();
return this;
}
//Close the database connection
public void close(){
myDBHelper.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//Add a new set of values to be inserted into the database.
public long insertRow(String task, String date,String startTime, String finishTime, String loc, String room, String des){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE,date);
initialValues.put(KEY_START_TIME,startTime);
initialValues.put(KEY_FINISH_TIME,finishTime);
initialValues.put(KEY_LOC,loc);
initialValues.put(KEY_ROOM,room);
initialValues.put(KEY_DES,des);
//Insert the data into the database
return db.insert(DATABASE_TABLE, null, initialValues);
}
//Delete a row from the database, by rowId(primary key)
public boolean deleteRow(long rowId){
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll(){
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if(c.moveToFirst()){
do{
deleteRow(c.getLong((int)rowId));
}while (c.moveToNext());
}
c.close();
}
//Return all data in the database.
public Cursor getAllRows(){
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, null, null, null, null, null, null);
if(c != null){
c.moveToFirst();
}
return c;
}
//Return all data in the database.
public Cursor getRow(long rowId){
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,where,null,null,null,null,null);
if(c != null){
c.moveToFirst();
}
return c;
}
//Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date,String startTime, String finishTime, String loc, String room, String des){
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK,task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_START_TIME,startTime);
newValues.put(KEY_FINISH_TIME,finishTime);
newValues.put(KEY_LOC, loc);
newValues.put(KEY_ROOM, room);
newValues.put(KEY_DES, des);
//Insert it into the database.
return db.update(DATABASE_TABLE,newValues,where,null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db){
_db.execSQL(DATABASE_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion){
Log.w(TAG, "Upgrading Application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
//Destroy old database;
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
//Recreates new database:
onCreate(_db);
}
}
}
主程序
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDb;
//Time zone
Time today = new Time(Time.getCurrentTimezone());
String etTasks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = "KKKK";
openDB();
populateListView();
//listViewItemClick();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//Opening the database
public void openDB(){
myDb = new DataBaseHelper(this);
myDb.open();
}
public void insertMe(String a, String s, String d, String f, String g, String h, String j){
(****ERROR HERE****)myDb.insertRow(a,s,d,f,g,h,j);
populateListView();
}
public void populateListView(){
//Cursor went into data base and got all the rows
Cursor cursor = myDb.getAllRows();
if(cursor.getCount() == 0){
Toast.makeText(this, "PARTYYY", Toast.LENGTH_LONG).show();
return;
}
//then places them into these arrays
String[] fromFieldNames = new String[]{
DataBaseHelper.KEY_START_TIME,DataBaseHelper.KEY_TASK,DataBaseHelper.KEY_LOC, DataBaseHelper.KEY_FINISH_TIME, DataBaseHelper.KEY_DATE, DataBaseHelper.KEY_ROOM, DataBaseHelper.KEY_DES};
int[] toViewIDs = new int[] {
R.id.sTime, R.id.food,R.id.loc, R.id.fTime, R.id.date, R.id.room, R.id.des};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor,fromFieldNames,toViewIDs,0);
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()){
String task = etTasks;
String fTime = "2pm";
String sTime = "12pm";
String loc = "UC";
String room = "103";
String des = "Fun Event Great Time";
today.setToNow();
String date = today.format("%Y-%m-%d %H:%M:%S");
myDb.updateRow(id,task,date,sTime,fTime,loc,room,des);
}
cursor.close();
}
private void listViewItemClick(){
ListView myList = (ListView)findViewById(R.id.listView);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F44336")));
return true;
}
else if (id == R.id.action_login)
{
Intent intent = new Intent(MainActivity.this, Clubs.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
俱乐部计划
public class Clubs extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
EditText clubName;
TextView nameError;
TextView dateError;
TextView locError;
TextView startError;
TextView endError;
TextView foodError;
TextView desError;
ImageButton add;
ImageButton date;
ImageButton loc;
ImageButton sTime;
ImageButton eTime;
ImageButton foodType;
Button des;
int year, month, day;
int hour, minute, eHour, eMinute;
String name, description = "", location = "---", food = "---";
ArrayList<Library> library = new ArrayList<>();
Library lib = new Library();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clubs);
des = (Button) findViewById(R.id.btnDes);
clubName = (EditText) findViewById(R.id.txtName);
nameError = (TextView) findViewById(R.id.lblNameError);
dateError = (TextView) findViewById(R.id.lblDError);
locError = (TextView) findViewById(R.id.lblLError);
startError = (TextView) findViewById(R.id.lblSError);
endError = (TextView) findViewById(R.id.lblFinError);
foodError = (TextView) findViewById(R.id.lblFoError);
desError = (TextView) findViewById(R.id.lblDesError);
add = (ImageButton) findViewById(R.id.btnAdd);
date = (ImageButton) findViewById(R.id.btnDate);
loc = (ImageButton) findViewById(R.id.btnLoc);
sTime = (ImageButton) findViewById(R.id.btnSTime);
eTime = (ImageButton) findViewById(R.id.btnETime);
foodType = (ImageButton) findViewById(R.id.btnFood);
date.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
final Calendar cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dDate = new DatePickerDialog(Clubs.this, dpickerListner, year, month, day);
dDate.show();
DatePickerDialog.OnDateSetListener dpickerListner
= new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year_x, int month_x, int day_x){
year = year_x;
month = month_x + 1;
day = day_x;
Toast.makeText(Clubs.this, year + "/" + month + "/" + day, Toast.LENGTH_LONG).show();
}
};
}
});
loc.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Clubs.this);
dialog.setTitle("Building");
dialog.setContentView(R.layout.description_dialog);
dialog.show();
Button done = (Button) dialog.findViewById(R.id.btnDone);
final EditText dDialog = (EditText) dialog.findViewById(R.id.txtDes);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
location = dDialog.getText().toString();
Toast.makeText(Clubs.this, "Saved " + location, Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
}
});
sTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog tTime = new TimePickerDialog(Clubs.this, sTimePickerListner, hour, minute,false);
tTime.show();
}
});
eTime.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
TimePickerDialog tTime = new TimePickerDialog(Clubs.this, eTimePickerListner, eHour, eMinute,false);
tTime.show();
}
});
foodType.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Clubs.this);
dialog.setTitle("Food");
dialog.setContentView(R.layout.food_spinner_dialog);
dialog.show();
final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner_food);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(Clubs.this, R.array.Food, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(Clubs.this);
Button done = (Button) dialog.findViewById(R.id.btnSpDoneFood);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
food = spinner.getSelectedItem().toString();
if (food.equals("---")) {
Toast.makeText(Clubs.this, "Pick a Food item!, " + food, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Clubs.this, "Saved, " + food, Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
}
});
des.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Clubs.this);
dialog.setTitle("Description of Event");
dialog.setContentView(R.layout.description_dialog);
dialog.show();
Button done = (Button) dialog.findViewById(R.id.btnDone);
final EditText dDialog = (EditText) dialog.findViewById(R.id.txtDes);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
description = dDialog.getText().toString();
Toast.makeText(Clubs.this, "Saved", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
}
});
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Food product = new Food(clubName.getText().toString());
if (clubName.getText().toString().equals("") || year == 0 || month == 0 || day == 0 || hour == 0 || eHour == 0 || location.equals("---") || description.equals("")) {
Toast.makeText(Clubs.this, "Input Error, check all fields", Toast.LENGTH_LONG).show();
}
else{
lib.addItem(year, month, day, location, hour, minute, eHour, eMinute, food, description);
Toast.makeText(Clubs.this, "Added Successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Clubs.this, "PARTYYY", Toast.LENGTH_LONG).show();
String dateBooked = (month + " " + day + ", " + year);
String startTime = (hour + ":" + minute);
String finishTime = (eHour + ":" + eMinute);
int room = 222;
String locc = "UC";
String dess = "LOOL";
String x = clubName.getText().toString();
Toast.makeText(Clubs.this,clubName.getText().toString() + "... " + startTime + " .." + finishTime + ".. loc: " + location + "..food: " +food + description, Toast.LENGTH_LONG).show();
(****ERROR HERE****)new MainActivity().insertMe("dude","a","a","a","a","a","a");**
Intent intent = new Intent(Clubs.this, MainActivity.class);
startActivity(intent);
}
if (clubName.getText().toString().equals("")) {
nameError.setVisibility(View.VISIBLE);
} else {
nameError.setVisibility(View.INVISIBLE);
}
if (year == 0 || month == 0 || day == 0) {
dateError.setVisibility(View.VISIBLE);
} else {
dateError.setVisibility(View.INVISIBLE);
}
if (hour == 0) {
startError.setVisibility(View.VISIBLE);
} else {
startError.setVisibility(View.INVISIBLE);
}
if (eHour == 0) {
endError.setVisibility(View.VISIBLE);
} else {
endError.setVisibility(View.INVISIBLE);
}
if (location.equals("---")) {
locError.setVisibility(View.VISIBLE);
} else {
locError.setVisibility(View.INVISIBLE);
}
if (description.equals("")) {
desError.setVisibility(View.VISIBLE);
} else {
desError.setVisibility(View.INVISIBLE);
}
}
});
}
//*****************************************************DATE PICKER***************************************************************
private DatePickerDialog.OnDateSetListener dpickerListner
= new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year_x, int month_x, int day_x){
year = year_x;
month = month_x + 1;
day = day_x;
Toast.makeText(Clubs.this, "Saved!", Toast.LENGTH_LONG).show();
}
};
//*****************************************************TIME PICKER***************************************************************
protected TimePickerDialog.OnTimeSetListener sTimePickerListner =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet (TimePicker view, int hour_x, int minute_x){
hour = hour_x;
minute = minute_x;
Toast.makeText(Clubs.this, "Saved!", Toast.LENGTH_LONG).show();
}
};
protected TimePickerDialog.OnTimeSetListener eTimePickerListner =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet (TimePicker view, int hour_x, int minute_x){
eHour = hour_x;
eMinute = minute_x;
Toast.makeText(Clubs.this,"Saved!", Toast.LENGTH_LONG).show();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_clubs, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_sign_out)
{
Intent intent = new Intent(Clubs.this, MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText = (TextView) view;
food = (String) myText.getText();
if (!food.equals("---")) {
Toast.makeText(this, "Food: " + food, Toast.LENGTH_LONG).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
答案 0 :(得分:1)
从未运行的Activity调用NullPointerException
方法导致DataBaseHelper
。
要使其工作,请在Clubs
活动中创建insertRow
类对象,然后调用DataBaseHelper myDb = new DataBaseHelper(this);
myDb.insertRow();
方法。
set(handles.text1,'String',sprintf('%-s\n%-s',a,Fs))