// MainActivity.java
package com.example.travelbookingapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.material.tabs.TabLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String PREFS_NAME = "TravelAppPrefs";
private static final String LOGGED_IN_USER = "loggedInUser";
private ViewPager viewPager;
private TabLayout tabLayout;
private DatabaseHelper dbHelper;
private boolean isLoggedIn = false;
private String currentUsername = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
// Check if user is already logged in
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
currentUsername = settings.getString(LOGGED_IN_USER, "");
isLoggedIn = !currentUsername.isEmpty();
// Initialize views
if (isLoggedIn) {
setupLoggedInView();
} else {
setupLoginView();
}
}
private void setupLoginView() {
setContentView(R.layout.activity_main);
final EditText etUsername = findViewById(R.id.etUsername);
final EditText etPassword = findViewById(R.id.etPassword);
Button btnLogin = findViewById(R.id.btnLogin);
Button btnSignup = findViewById(R.id.btnSignup);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(MainActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
return;
}
if (dbHelper.checkUser(username, password)) {
// Save login state
saveLoginState(username);
// Setup logged in view
currentUsername = username;
isLoggedIn = true;
setupLoggedInView();
} else {
Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_SHORT).show();
}
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(MainActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
return;
}
if (dbHelper.checkUserExists(username)) {
Toast.makeText(MainActivity.this, "Username already exists", Toast.LENGTH_SHORT).show();
return;
}
if (dbHelper.addUser(username, password)) {
Toast.makeText(MainActivity.this, "User registered successfully", Toast.LENGTH_SHORT).show();
// Save login state
saveLoginState(username);
// Setup logged in view
currentUsername = username;
isLoggedIn = true;
setupLoggedInView();
} else {
Toast.makeText(MainActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupLoggedInView() {
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
// Set up ViewPager with TabLayout
setupViewPager();
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager() {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new BookTicketFragment(), "Book Ticket");
adapter.addFragment(new BookingsFragment(), "My Bookings");
adapter.addFragment(new ProfileFragment(), "Profile");
viewPager.setAdapter(adapter);
}
private void saveLoginState(String username) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(LOGGED_IN_USER, username);
editor.apply();
}
private void clearLoginState() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove(LOGGED_IN_USER);
editor.apply();
}
// Fragment adapter for ViewPager
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List fragmentList = new ArrayList<>();
private final List fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
// BookTicket Fragment
public static class BookTicketFragment extends Fragment {
private boolean isTicketBooked = false;
private String bookingDetails = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (isTicketBooked) {
return inflateTicketDetailsView(inflater, container);
} else {
return inflateBookingFormView(inflater, container);
}
}
private View inflateBookingFormView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_book_ticket, container, false);
final EditText etName = view.findViewById(R.id.etName);
final EditText etAge = view.findViewById(R.id.etAge);
final DatePicker datePicker = view.findViewById(R.id.datePicker);
final TimePicker timePicker = view.findViewById(R.id.timePicker);
final Spinner spinnerSeatType = view.findViewById(R.id.spinnerSeatType);
final CheckBox checkboxMeal = view.findViewById(R.id.checkboxMeal);
final CheckBox checkboxLuggage = view.findViewById(R.id.checkboxLuggage);
final RadioGroup radioGroupClass = view.findViewById(R.id.radioGroupClass);
final Button btnOptions = view.findViewById(R.id.btnOptions);
final Button btnSubmit = view.findViewById(R.id.btnSubmit);
// Setup spinner for seat type
ArrayAdapter adapter = ArrayAdapter.createFromResource(
getContext(),
R.array.seat_types,
android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeatType.setAdapter(adapter);
// Setup popup menu for additional options
btnOptions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(getContext(), v);
popup.getMenuInflater().inflate(R.menu.booking_options_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getContext(), "Selected: " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
});
// Submit booking
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = etName.getText().toString().trim();
String ageStr = etAge.getText().toString().trim();
if (name.isEmpty() || ageStr.isEmpty()) {
Toast.makeText(getContext(), "Please enter name and age", Toast.LENGTH_SHORT).show();
return;
}
int age = Integer.parseInt(ageStr);
// Get selected date
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
String dateStr = dateFormat.format(date);
// Get selected time
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
String timeStr = String.format(Locale.US, "%02d:%02d", hour, minute);
// Get seat type
String seatType = spinnerSeatType.getSelectedItem().toString();
// Get additional options
boolean hasMeal = checkboxMeal.isChecked();
boolean hasLuggage = checkboxLuggage.isChecked();
// Get class
int selectedRadioId = radioGroupClass.getCheckedRadioButtonId();
RadioButton radioButton = view.findViewById(selectedRadioId);
String travelClass = radioButton != null ? radioButton.getText().toString() : "Economy";
// Create booking details
bookingDetails = "Name: " + name + "\n" +
"Age: " + age + "\n" +
"Date: " + dateStr + "\n" +
"Time: " + timeStr + "\n" +
"Seat Type: " + seatType + "\n" +
"Class: " + travelClass + "\n" +
"Meal Included: " + (hasMeal ? "Yes" : "No") + "\n" +
"Extra Luggage: " + (hasLuggage ? "Yes" : "No");
// Save to database
DatabaseHelper dbHelper = new DatabaseHelper(getContext());
MainActivity activity = (MainActivity) getActivity();
String username = activity.currentUsername;
long bookingId = dbHelper.addBooking(username, name, age, dateStr, timeStr,
seatType, travelClass, hasMeal, hasLuggage);
if (bookingId != -1) {
Toast.makeText(getContext(), "Booking successful", Toast.LENGTH_SHORT).show();
isTicketBooked = true;
// Reload the fragment with ticket details view
ViewGroup viewGroup = (ViewGroup) view.getParent();
viewGroup.removeView(view);
View newView = inflateTicketDetailsView(getLayoutInflater(), viewGroup);
viewGroup.addView(newView);
} else {
Toast.makeText(getContext(), "Booking failed", Toast.LENGTH_SHORT).show();
}
}
});
registerForContextMenu(view.findViewById(R.id.tvContextMenu));
return view;
}
private View inflateTicketDetailsView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_ticket_details, container, false);
TextView tvTicketDetails = view.findViewById(R.id.tvTicketDetails);
Button btnBack = view.findViewById(R.id.btnBack);
tvTicketDetails.setText(bookingDetails);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isTicketBooked = false;
// Reload the fragment with booking form view
ViewGroup viewGroup = (ViewGroup) view.getParent();
if (viewGroup != null) {
viewGroup.removeView(view);
View newView = inflateBookingFormView(getLayoutInflater(), viewGroup);
viewGroup.addView(newView);
}
}
});
return view;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_info:
Toast.makeText(getContext(), "Travel information", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_help:
Toast.makeText(getContext(), "Help center", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
// Bookings Fragment
public static class BookingsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bookings, container, false);
ListView listView = view.findViewById(R.id.listViewBookings);
DatabaseHelper dbHelper = new DatabaseHelper(getContext());
MainActivity activity = (MainActivity) getActivity();
String username = activity.currentUsername;
List bookings = dbHelper.getBookings(username);
BookingsAdapter adapter = new BookingsAdapter(getContext(), bookings);
listView.setAdapter(adapter);
return view;
}
private static class BookingsAdapter extends BaseAdapter {
private Context context;
private List bookings;
public BookingsAdapter(Context context, List bookings) {
this.context = context;
this.bookings = bookings;
}
@Override
public int getCount() {
return bookings.size();
}
@Override
public Object getItem(int position) {
return bookings.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_booking, parent, false);
}
TextView tvName = convertView.findViewById(R.id.tvBookingName);
TextView tvDate = convertView.findViewById(R.id.tvBookingDate);
TextView tvDetails = convertView.findViewById(R.id.tvBookingDetails);
Booking booking = bookings.get(position);
tvName.setText(booking.name);
tvDate.setText(booking.date + " at " + booking.time);
tvDetails.setText("Class: " + booking.travelClass + ", Seat: " + booking.seatType);
return convertView;
}
}
}
// Profile Fragment
public static class ProfileFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
TextView tvUsername = view.findViewById(R.id.tvUsername);
Button btnLogout = view.findViewById(R.id.btnLogout);
MainActivity activity = (MainActivity) getActivity();
tvUsername.setText("Welcome, " + activity.currentUsername);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.clearLoginState();
activity.isLoggedIn = false;
activity.currentUsername = "";
activity.setupLoginView();
}
});
return view;
}
}
// DatabaseHelper class for SQLite operations
public static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "TravelBooking.db";
private static final int DATABASE_VERSION = 1;
// User table
private static final String TABLE_USERS = "users";
private static final String COLUMN_USER_ID = "id";
private static final String COLUMN_USER_USERNAME = "username";
private static final String COLUMN_USER_PASSWORD = "password";
// Booking table
private static final String TABLE_BOOKINGS = "bookings";
private static final String COLUMN_BOOKING_ID = "id";
private static final String COLUMN_BOOKING_USERNAME = "username";
private static final String COLUMN_BOOKING_NAME = "name";
private static final String COLUMN_BOOKING_AGE = "age";
private static final String COLUMN_BOOKING_DATE = "date";
private static final String COLUMN_BOOKING_TIME = "time";
private static final String COLUMN_BOOKING_SEAT_TYPE = "seat_type";
private static final String COLUMN_BOOKING_CLASS = "travel_class";
private static final String COLUMN_BOOKING_MEAL = "has_meal";
private static final String COLUMN_BOOKING_LUGGAGE = "has_luggage";
// Create table queries
private static final String CREATE_TABLE_USERS =
"CREATE TABLE " + TABLE_USERS + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USER_USERNAME + " TEXT UNIQUE,"
+ COLUMN_USER_PASSWORD + " TEXT"
+ ")";
private static final String CREATE_TABLE_BOOKINGS =
"CREATE TABLE " + TABLE_BOOKINGS + "("
+ COLUMN_BOOKING_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_BOOKING_USERNAME + " TEXT,"
+ COLUMN_BOOKING_NAME + " TEXT,"
+ COLUMN_BOOKING_AGE + " INTEGER,"
+ COLUMN_BOOKING_DATE + " TEXT,"
+ COLUMN_BOOKING_TIME + " TEXT,"
+ COLUMN_BOOKING_SEAT_TYPE + " TEXT,"
+ COLUMN_BOOKING_CLASS + " TEXT,"
+ COLUMN_BOOKING_MEAL + " INTEGER,"
+ COLUMN_BOOKING_LUGGAGE + " INTEGER"
+ ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create tables
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_BOOKINGS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older tables if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKINGS);
// Create tables again
onCreate(db);
}
// Add a new user
public boolean addUser(String username, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_USERNAME, username);
values.put(COLUMN_USER_PASSWORD, password);
// Insert row
long id = db.insert(TABLE_USERS, null, values);
db.close();
return id != -1;
}
// Check if user exists
public boolean checkUserExists(String username) {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {COLUMN_USER_ID};
String selection = COLUMN_USER_USERNAME + " = ?";
String[] selectionArgs = {username};
Cursor cursor = db.query(
TABLE_USERS,
columns,
selection,
selectionArgs,
null,
null,
null
);
int count = cursor.getCount();
cursor.close();
db.close();
return count > 0;
}
// Check user credentials
public boolean checkUser(String username, String password) {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {COLUMN_USER_ID};
String selection = COLUMN_USER_USERNAME + " = ? AND " + COLUMN_USER_PASSWORD + " = ?";
String[] selectionArgs = {username, password};
Cursor cursor = db.query(
TABLE_USERS,
columns,
selection,
selectionArgs,
null,
null,
null
);
int count = cursor.getCount();
cursor.close();
db.close();
return count > 0;
}
// Add a new booking
public long addBooking(String username, String name, int age, String date, String time,
String seatType, String travelClass, boolean hasMeal, boolean hasLuggage) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_BOOKING_USERNAME, username);
values.put(COLUMN_BOOKING_NAME, name);
values.put(COLUMN_BOOKING_AGE, age);
values.put(COLUMN_BOOKING_DATE, date);
values.put(COLUMN_BOOKING_TIME, time);
values.put(COLUMN_BOOKING_SEAT_TYPE, seatType);
values.put(COLUMN_BOOKING_CLASS, travelClass);
values.put(COLUMN_BOOKING_MEAL, hasMeal ? 1 : 0);
values.put(COLUMN_BOOKING_LUGGAGE, hasLuggage ? 1 : 0);
// Insert row
long id = db.insert(TABLE_BOOKINGS, null, values);
db.close();
return id;
}
// Get all bookings for a user
public List getBookings(String username) {
List bookings = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_BOOKINGS +
" WHERE " + COLUMN_BOOKING_USERNAME + " = ?" +
" ORDER BY " + COLUMN_BOOKING_ID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{username});
if (cursor.moveToFirst()) {
do {
Booking booking = new Booking();
booking.id = cursor.getInt(cursor.getColumnIndex(COLUMN_BOOKING_ID));
booking.name = cursor.getString(cursor.getColumnIndex(COLUMN_BOOKING_NAME));
booking.age = cursor.getInt(cursor.getColumnIndex(COLUMN_BOOKING_AGE));
booking.date = cursor.getString(cursor.getColumnIndex(COLUMN_BOOKING_DATE));
booking.time = cursor.getString(cursor.getColumnIndex(COLUMN_BOOKING_TIME));
booking.seatType = cursor.getString(cursor.getColumnIndex(COLUMN_BOOKING_SEAT_TYPE));
booking.travelClass = cursor.getString(cursor.getColumnIndex(COLUMN_BOOKING_CLASS));
booking.hasMeal = cursor.getInt(cursor.getColumnIndex(COLUMN_BOOKING_MEAL)) == 1;
booking.hasLuggage = cursor.getInt(cursor.getColumnIndex(COLUMN_BOOKING_LUGGAGE)) == 1;
bookings.add(booking);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return bookings;
}
}
// Booking model class
public static class Booking {
public int id;
public String name;
public int age;
public String date;
public String time;
public String seatType;
public String travelClass;
public boolean hasMeal;
public boolean hasLuggage;
}
}
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp">
Window
Middle
Aisle
Extra Legroom
dependencies {
// ... other dependencies
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.3.0'
}
strings.xml
Travel Booking App
This error is occurring because you're trying to use R.id.menu_info in a switch statement, but it's not being recognized as a constant expression. This is happening because the context menu is not properly connected to your fragment.
Let's fix this by modifying your BookTicketFragment class to properly handle the context menu. Here's what we need to change:
First, we need to register the context menu with the fragment's view
Then, we need to provide proper implementation of the onCreateContextMenu method
Finally, we need to fix the onContextItemSelected method
// BookTicket Fragment
public static class BookTicketFragment extends Fragment {
private boolean isTicketBooked = false;
private String bookingDetails = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (isTicketBooked) {
return inflateTicketDetailsView(inflater, container);
} else {
return inflateBookingFormView(inflater, container);
}
}
private View inflateBookingFormView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_book_ticket, container, false);
// All other initialization code remains the same
// Register context menu
TextView tvContextMenu = view.findViewById(R.id.tvContextMenu);
registerForContextMenu(tvContextMenu);
return view;
}
// Add this method to create the context menu
@Override
public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
android.view.MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
// Modify this method to handle the menu item selection
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_info:
Toast.makeText(getContext(), "Travel information", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_help:
Toast.makeText(getContext(), "Help center", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
// The rest of your code remains the same
}
android:id="@+id/menu_info"
android:title="Travel Information" />
android:id="@+id/menu_help"
android:title="Help Center" />