0

I have an application that supposed to take the text that the user enters from 4 EditTexts and a Spinner, and create a new item in the database when a button is clicked. (Image Below) enter image description here

I have created a method in my database helper class that adds a new item, so in this activity I create a new item, and then pass that item to the method that should create it in the database. But for some reason weird text appear on the screen instead of a new item in the RecyclerView.

enter image description here

I don't know why I get the strings from the editTexts and the int (Which is the Arrival Time) and the string from the spinner and I pass it to a new item (Train) but this error keeps happening.

Here are my DatabaseHelper Class:

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

Here is the activity where we add a new item (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));
}

And this is the MainActivity Class:

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

}

Thanks in advance and if you need more code let me know.

1 Answer 1

2

The problem was I forgot to do .getText() before doing .toString() example:

mPlatformEt.getText().toString();

instead of

mPlatformEt.toString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.