从EditTexts向SQLite数据库添加新项时出错

时间:2018-04-29 03:12:08

标签: java android sqlite android-studio

我有一个应用程序,它应该从4 EditTexts和Spinner中获取用户输入的文本,并在单击按钮时在数据库中创建一个新项目。 (下图) enter image description here

我在我的数据库助手类中创建了一个添加新项的方法,因此在此活动中我创建了一个新项,然后将该项传递给应该在数据库中创建它的方法。但由于某种原因,屏幕上会出现奇怪的文字而不是RecyclerView中的新项目。

enter image description here

我不知道为什么我从editTexts和int(这是到达时间)和旋转器中的字符串中获取字符串,然后将其传递给新项目(Train),但此错误仍在继续

这是我的DatabaseHelper类:

public class TrainDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "train.db";
public static final String TABLE_NAME = "train";
public static final String COLUMN_ID ="_id";
public static final String COLUMN_PLATFORM = "platform";
public static final String COLUMN_ARRIVAL_TIME = "arrival_time";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_DESTINATION_TIME = "destination_time";
public static final String[] COLUMNS = {COLUMN_ID, COLUMN_PLATFORM, COLUMN_ARRIVAL_TIME
, COLUMN_STATUS,COLUMN_DESTINATION,COLUMN_DESTINATION_TIME};
private static TrainDatabaseHelper sInstance;

public synchronized static TrainDatabaseHelper getInstance(Context context) {
    if (sInstance == null){
        sInstance = new TrainDatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
}

private TrainDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " ("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_PLATFORM + " TEXT, "
            + COLUMN_ARRIVAL_TIME + " INTEGER, "
            + COLUMN_STATUS+ " TEXT, "
            + COLUMN_DESTINATION + " TEXT, "
            + COLUMN_DESTINATION_TIME + " TEXT"
            + ")"
    );

    addTrain(db, new Train(0, "Albion Park Platform 1", 3,"On Time",
            "Allawah", "14:11"));
    addTrain(db, new Train(1, "Arncliffe Platform 2", 4, "Late",
           "Central", "14:34"));
    addTrain(db, new Train(2, "Artarmion Platform 3", 7, "On Time",
           "Ashfield", "15:01"));
    addTrain(db, new Train(3, "Berowra Platform 4", 12, "Late",
            "Beverly", "15:18"));
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion){
        case 1:
            db.execSQL("alter table " + TABLE_NAME + " add column description TEXT");
        case 2:
            db.execSQL("alter table " + TABLE_NAME + " add column air_conditioned TEXT");
    }
}
public void addTrain(Train train){
   addTrain(getWritableDatabase(), train);
}
private void addTrain(SQLiteDatabase db, Train train){
    ContentValues values = new ContentValues();
    values.put(COLUMN_PLATFORM, train.getPlatform());
    values.put(COLUMN_ARRIVAL_TIME, train.getArrivalTime());
    values.put(COLUMN_STATUS, train.getStatus());
    values.put(COLUMN_DESTINATION, train.getDestination());
    values.put(COLUMN_DESTINATION_TIME, train.getDestinationTime());
    db.insert(TABLE_NAME,null,values);
}
public void deleteTrains (){
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_NAME,null,null);
}
public Train getTrain(int position){
    return getTrains().get(position);
}
public List<Train> getTrains(){
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
    List<Train> trains = new ArrayList<>();
    if (cursor.moveToFirst()) {
        do {
            Train train = new Train(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),
                    cursor.getString(3),cursor.getString(4),cursor.getString(5));
            trains.add(train);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return trains;
}

以下是我们添加新项目(Train)的活动:

public class AddTrainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mPlatformEt, mArrivalEt, mDestinationEt, mDestinationTimeEt;
private String mStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_train_activity);
    mPlatformEt = findViewById(R.id.platform_entry);
    mArrivalEt = findViewById(R.id.arrival_time_entry);
    mDestinationEt = findViewById(R.id.destination_entry);
    mDestinationTimeEt = findViewById(R.id.destination_time_entry);
    mSpinner = findViewById(R.id.status_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this,
            R.array.status_array, android.R.layout.simple_spinner_item);
    // Apply the adapter to the spinner
    mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
    mSpinner.setAdapter(mAdapter);
    mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    mStatus = getString(R.string.status_on_time);
                    break;
                case 1:
                    mStatus = getString(R.string.status_late);
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(AddTrainActivity.this, R.string.status_toast, Toast.LENGTH_LONG).show();
        }
    });
}

public void addTrainButton (View view) {
    int arrivalTime = Integer.valueOf(mArrivalEt.toString());
    String platform = mPlatformEt.toString();
    String destination = mDestinationEt.toString();
    String destinationTime =  mDestinationTimeEt.toString();
    Train train = new Train(4,platform,arrivalTime, mStatus,
            destination ,destinationTime);
    TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
    helper.addTrain(train);
    Toast.makeText(this, R.string.add_train_toast, Toast.LENGTH_SHORT).show();
    goBackHome();
}

public void cancelButton(View view) {
    goBackHome();
}
public void goBackHome(){
    startActivity(new Intent(AddTrainActivity.this, MainActivity.class));
}

这是MainActivity类:

public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mTrainsRv = findViewById(R.id.train_rv);
    mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
    mTrainAdapter = new TrainAdapter(this);
    mTrainsRv.setAdapter(mTrainAdapter);

    FloatingActionButton fab = findViewById(R.id.fab);
    /** a FAB onClick Listener that starts a new activity to add a train */
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,AddTrainActivity.class));
        }
    });
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    /* Handle action bar item clicks here */
    switch (item.getItemId()) {
        case R.id.action_delete:
            // TODO deleting all trains from database
            mTrainAdapter.notifyDataSetChanged();
            return true;
        case R.id.action_refresh:
            return true;
        case R.id.action_quit:
            Toast.makeText(this, R.string.quit_menu,
                    Toast.LENGTH_LONG).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onResume() {
    super.onResume();
    TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);

}

提前致谢,如果您需要更多代码,请与我们联系。

1 个答案:

答案 0 :(得分:2)

问题是我在做.toString()之前忘了做.getText() 例如:

mPlatformEt.getText().toString();

而不是

mPlatformEt.toString();