skip to Main Content

I’m developing an Android application in Android Studio and I’m in need of assistance with implementing several fundamental functionalities. Specifically, I require guidance on:

Using Intents for navigation between activities.
Displaying messages to the user using AlertDialog.
Sending notifications using NotificationManager.
Implementing MediaPlayer for audio playback.
Creating and managing a SQLite database, including table creation, inserting values, and fetching data based on conditions, using a DatabaseHelper class.
I’ve explored documentation and tutorials for each of these topics, but I’m struggling to integrate them effectively into my project.

Could someone please provide comprehensive examples or code snippets demonstrating the proper implementation of these functionalities in Android Studio, either in Java or Kotlin? Additionally, any insights into best practices or common pitfalls to avoid would be greatly appreciated.

I’ve explored documentation and tutorials for each of these topics, but I’m struggling to integrate them effectively into my project.

4

Answers


  1. Chosen as BEST ANSWER
    1. Example of a database helper program --

      package com.example.l7q1;

      import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;

      public class DatabaseHelper extends SQLiteOpenHelper {

      private static final String DATABASE_NAME = "student.db";
      private static final int DATABASE_VERSION = 1;
      
      private static final String TABLE_NAME = "student";
      private static final String COLUMN_ID = "id";
      private static final String COLUMN_ROLL_NUMBER = "roll_number";
      private static final String COLUMN_NAME = "name";
      private static final String COLUMN_MARKS = "marks";
      
      public DatabaseHelper(Context context) {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
      
      @Override
      public void onCreate(SQLiteDatabase db) {
          String createTableQuery = "CREATE TABLE " + TABLE_NAME + " ("
                  + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                  + COLUMN_ROLL_NUMBER + " VARCHAR, "
                  + COLUMN_NAME + " VARCHAR, "
                  + COLUMN_MARKS + " VARCHAR)";
          db.execSQL(createTableQuery);
      }
      
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
          onCreate(db);
      }
      
      public boolean addStudent(String rollNumber, String name, String marks) {
          SQLiteDatabase db = this.getWritableDatabase();
          ContentValues contentValues = new ContentValues();
          contentValues.put(COLUMN_ROLL_NUMBER, rollNumber);
          contentValues.put(COLUMN_NAME, name);
          contentValues.put(COLUMN_MARKS, marks);
          long result = db.insert(TABLE_NAME, null, contentValues);
          return result != -1;
      }
      
      public Cursor getAllStudents() {
          SQLiteDatabase db = this.getWritableDatabase();
          return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
      }
      
      // Inside DatabaseHelper.java
      public boolean updateStudent(String rollNumber, String name, String marks) {
          SQLiteDatabase db = this.getWritableDatabase();
          ContentValues values = new ContentValues();
          values.put(COLUMN_NAME, name);
          values.put(COLUMN_MARKS, marks);
          int affectedRows = db.update(TABLE_NAME, values, COLUMN_ROLL_NUMBER + "=?", new String[]{rollNumber});
          return affectedRows > 0;
      }
      
      
      public boolean deleteStudent(String id) {
          SQLiteDatabase db = this.getWritableDatabase();
          int deletedRows = db.delete(TABLE_NAME, "id=?", new String[]{id});
          return deletedRows > 0;
      }
      

      }

    2. Popup Menu example --

    3. Basic layout for first page with spinner example --

      <Spinner
          android:id="@+id/spinner"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_centerInParent="true"/>
      
      <Button
          android:id="@+id/okButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="OK"
          android:layout_below="@id/spinner"
          android:layout_alignParentStart="true"/>
      
      <Button
          android:id="@+id/clickMeButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Click Me"
          android:layout_below="@id/spinner"
          android:layout_alignParentEnd="true"/>
      
    4. main activity.java --

      import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.PopupMenu; import android.widget.Spinner; import android.widget.Toast;

      import androidx.appcompat.app.AppCompatActivity;

      import java.util.ArrayList; import java.util.List;

      public class MainActivity extends AppCompatActivity {

      Spinner spinner;
      Button okButton, clickMeButton;
      List<String> itemsList = new ArrayList<>();
      List<Integer> costsList = new ArrayList<>();
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          spinner = findViewById(R.id.spinner);
          okButton = findViewById(R.id.okButton);
          clickMeButton = findViewById(R.id.clickMeButton);
      
          // Define items and their costs
          String[] items = {"Item1 - $25", "Item2 - $30", "Item3 - $15"};
      
          // Populate Spinner with items and costs
          ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
          spinner.setAdapter(adapter);
      
          // OK button click listener
          okButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  String selectedItem = spinner.getSelectedItem().toString();
                  String[] parts = selectedItem.split(" - ");
                  String itemName = parts[0];
                  int itemCost = Integer.parseInt(parts[1].replace("$", ""));
                  itemsList.add(itemName);
                  costsList.add(itemCost);
              }
          });
      
          // Click Me button click listener
          clickMeButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  // Show a PopupMenu
                  PopupMenu popupMenu = new PopupMenu(MainActivity.this, clickMeButton);
                  popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
                  popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                      @Override
                      public boolean onMenuItemClick(MenuItem item) {
                          int itemId = item.getItemId();
                          if (itemId == R.id.menu_compute_average) {
                              computeAndDisplayAverage();
                              return true;
                          } else if (itemId == R.id.menu_list_values_above_average) {
                              listValuesAboveAverage();
                              return true;
                          } else if (itemId == R.id.menu_list_values_below_average) {
                              listValuesBelowAverage();
                              return true;
                          }
                          return false;
                      }
                  });
                  popupMenu.show();
              }
          });
      }
      
      private void computeAndDisplayAverage() {
          if (costsList.isEmpty()) {
              Toast.makeText(MainActivity.this, "No items selected", Toast.LENGTH_SHORT).show();
              return;
          }
      
          int totalCost = 0;
          for (int cost : costsList) {
              totalCost += cost;
          }
          double average = totalCost / (double) costsList.size();
          Toast.makeText(MainActivity.this, "Average cost: $" + average, Toast.LENGTH_SHORT).show();
      }
      
      
      private void listValuesAboveAverage() {
          double totalCost = 0;
          for (int cost : costsList) {
              totalCost += cost;
          }
          double average = totalCost / costsList.size();
      
          List<String> aboveAverageItems = new ArrayList<>();
          for (int i = 0; i < costsList.size(); i++) {
              if (costsList.get(i) > average) {
                  aboveAverageItems.add(itemsList.get(i) + " - $" + costsList.get(i));
              }
          }
          // Display above average items in a ListView or do something else with them
          Toast.makeText(MainActivity.this, "Items above average: " + aboveAverageItems.toString(), Toast.LENGTH_SHORT).show();
      }
      
      private void listValuesBelowAverage() {
          double totalCost = 0;
          for (int cost : costsList) {
              totalCost += cost;
          }
          double average = totalCost / costsList.size();
      
          List<String> belowAverageItems = new ArrayList<>();
          for (int i = 0; i < costsList.size(); i++) {
              if (costsList.get(i) < average) {
                  belowAverageItems.add(itemsList.get(i) + " - $" + costsList.get(i));
              }
          }
          // Display below average items in a ListView or do something else with them
          Toast.makeText(MainActivity.this, "Items below average: " + belowAverageItems.toString(), Toast.LENGTH_SHORT).show();
      }
      

      }


  2. Example of another db oriented student details app —

    Mainactivity.java–

    package com.example.l7q1;
    
    import android.os.Bundle;
    
    import androidx.activity.EdgeToEdge;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.graphics.Insets;
    import androidx.core.view.ViewCompat;
    import androidx.core.view.WindowInsetsCompat;
    
    import android.database.Cursor;
    import android.os.Bundle;
    import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        private DatabaseHelper dbHelper;
        private ListView studentListView;
        private ArrayAdapter<String> adapter;
        private List<String> studentDetailsList;
        private EditText rollNumberEditText, nameEditText, marksEditText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            dbHelper = new DatabaseHelper(this);
    
            rollNumberEditText = findViewById(R.id.rollNumberEditText);
            nameEditText = findViewById(R.id.nameEditText);
            marksEditText = findViewById(R.id.marksEditText);
    
            Button addButton = findViewById(R.id.addButton);
            Button updateButton = findViewById(R.id.updateButton);
            Button deleteButton = findViewById(R.id.deleteButton);
    
            studentListView = findViewById(R.id.studentListView);
            studentDetailsList = new ArrayList<>();
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, studentDetailsList);
            studentListView.setAdapter(adapter);
    
            loadStudentList();
    
            addButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String rollNumber = rollNumberEditText.getText().toString().trim();
                    String name = nameEditText.getText().toString().trim();
                    String marks = marksEditText.getText().toString().trim();
                    if (!rollNumber.isEmpty() && !name.isEmpty() && !marks.isEmpty()) {
                        boolean success = dbHelper.addStudent(rollNumber, name, marks);
                        if (success) {
                            Toast.makeText(MainActivity.this, "Student added successfully", Toast.LENGTH_SHORT).show();
                            loadStudentList();
                            clearFields();
                        } else {
                            Toast.makeText(MainActivity.this, "Failed to add student", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
            // Inside MainActivity.java
            updateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String rollNumber = rollNumberEditText.getText().toString().trim();
                    String name = nameEditText.getText().toString().trim();
                    String marks = marksEditText.getText().toString().trim();
                    if (!rollNumber.isEmpty() && !name.isEmpty() && !marks.isEmpty()) {
                        boolean success = dbHelper.updateStudent(rollNumber, name, marks);
                        if (success) {
                            Toast.makeText(MainActivity.this, "Student updated successfully", Toast.LENGTH_SHORT).show();
                            loadStudentList();
                            clearFields();
                        } else {
                            Toast.makeText(MainActivity.this, "Failed to update student", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String rollNumber = rollNumberEditText.getText().toString().trim();
                    if (!rollNumber.isEmpty()) {
                        boolean success = dbHelper.deleteStudent(rollNumber);
                        if (success) {
                            Toast.makeText(MainActivity.this, "Student deleted successfully", Toast.LENGTH_SHORT).show();
                            loadStudentList();
                            clearFields();
                        } else {
                            Toast.makeText(MainActivity.this, "Failed to delete student", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "Please enter roll number to delete", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
            studentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String studentDetails = adapter.getItem(position);
                    // You can parse the student details if needed
                    Toast.makeText(MainActivity.this, "Clicked on: " + studentDetails, Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        private void loadStudentList() {
            studentDetailsList.clear();
            Cursor cursor = dbHelper.getAllStudents();
            if (cursor.moveToFirst()) {
                do {
                    String id = cursor.getString(0);
                    String rollNumber = cursor.getString(1);
                    String name = cursor.getString(2);
                    String marks = cursor.getString(3);
                    String studentDetails = "ID: " + id + "nRoll Number: " + rollNumber + "nName: " + name + "nMarks: " + marks;
                    studentDetailsList.add(studentDetails);
                } while (cursor.moveToNext());
                adapter.notifyDataSetChanged();
            } else {
                Toast.makeText(this, "No students found", Toast.LENGTH_SHORT).show();
            }
            cursor.close();
        }
    
        private void clearFields() {
            rollNumberEditText.setText("");
            nameEditText.setText("");
            marksEditText.setText("");
        }
    }
    

    Databasehelper.java —

    package com.example.l7q1;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DatabaseHelper extends SQLiteOpenHelper {
    
        private static final String DATABASE_NAME = "student.db";
        private static final int DATABASE_VERSION = 1;
    
        private static final String TABLE_NAME = "student";
        private static final String COLUMN_ID = "id";
        private static final String COLUMN_ROLL_NUMBER = "roll_number";
        private static final String COLUMN_NAME = "name";
        private static final String COLUMN_MARKS = "marks";
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String createTableQuery = "CREATE TABLE " + TABLE_NAME + " ("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + COLUMN_ROLL_NUMBER + " VARCHAR, "
                    + COLUMN_NAME + " VARCHAR, "
                    + COLUMN_MARKS + " VARCHAR)";
            db.execSQL(createTableQuery);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    
        public boolean addStudent(String rollNumber, String name, String marks) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(COLUMN_ROLL_NUMBER, rollNumber);
            contentValues.put(COLUMN_NAME, name);
            contentValues.put(COLUMN_MARKS, marks);
            long result = db.insert(TABLE_NAME, null, contentValues);
            return result != -1;
        }
    
        public Cursor getAllStudents() {
            SQLiteDatabase db = this.getWritableDatabase();
            return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        }
    
        // Inside DatabaseHelper.java
        public boolean updateStudent(String rollNumber, String name, String marks) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME, name);
            values.put(COLUMN_MARKS, marks);
            int affectedRows = db.update(TABLE_NAME, values, COLUMN_ROLL_NUMBER + "=?", new String[]{rollNumber});
            return affectedRows > 0;
        }
    
    
        public boolean deleteStudent(String id) {
            SQLiteDatabase db = this.getWritableDatabase();
            int deletedRows = db.delete(TABLE_NAME, "id=?", new String[]{id});
            return deletedRows > 0;
        }
    }
    

    Activity_main.xml —

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <EditText
            android:id="@+id/rollNumberEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Roll Number"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"/>
    
        <EditText
            android:id="@+id/nameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Name"
            android:layout_below="@id/rollNumberEditText"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"/>
    
        <EditText
            android:id="@+id/marksEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Marks"
            android:layout_below="@id/nameEditText"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"/>
    
        <Button
            android:id="@+id/addButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add"
            android:layout_below="@id/marksEditText"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"/>
    
        <Button
            android:id="@+id/updateButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update"
            android:layout_below="@id/addButton"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"/>
    
        <Button
            android:id="@+id/deleteButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:layout_below="@id/updateButton"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp"/>
    
        <ListView
            android:id="@+id/studentListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/deleteButton"
            android:layout_marginTop="16dp"
            android:divider="@null"
            android:dividerHeight="0dp"/>
    
    </RelativeLayout>
    

    .

    Login or Signup to reply.
  3. Media player
    Main Activity.java

    package com.example.l6q2;
    
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    import androidx.activity.EdgeToEdge;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.graphics.Insets;
    import androidx.core.view.ViewCompat;
    import androidx.core.view.WindowInsetsCompat;
    
    
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        private ListView songListView;
        private MediaPlayer mediaPlayer;
        private int currentPosition = -1;
    
        private int[] songResources = {R.raw.song1, R.raw.song2, R.raw.song3}; // Example: raw resources of songs
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            songListView = findViewById(R.id.songListView);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.song_titles, android.R.layout.simple_list_item_1);
            songListView.setAdapter(adapter);
    
            songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                    playSong(songResources[position]);
                    currentPosition = position;
                }
            });
    
            // Initialize media controls
            Button playButton = findViewById(R.id.playButton);
            Button pauseButton = findViewById(R.id.pauseButton);
            Button stopButton = findViewById(R.id.stopButton);
    
            playButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                    }
                }
            });
    
            pauseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                    }
                }
            });
    
            stopButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer != null) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }
            });
        }
    
        private void playSong(int songResource) {
            mediaPlayer = MediaPlayer.create(this, songResource);
            mediaPlayer.start();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    }
    

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ListView
            android:id="@+id/songListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_alignParentBottom="true">
    
            <Button
                android:id="@+id/playButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Play" />
    
            <Button
                android:id="@+id/pauseButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pause" />
    
            <Button
                android:id="@+id/stopButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stop" />
    
        </LinearLayout>
    
    </RelativeLayout>
    

    activity_player.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <!-- Media controls -->
        <Button
            android:id="@+id/playButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Play"
            android:layout_centerInParent="true"/>
    
        <Button
            android:id="@+id/pauseButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Pause"
            android:layout_below="@id/playButton"
            android:layout_marginTop="16dp"
            android:layout_centerHorizontal="true"/>
    
        <Button
            android:id="@+id/stopButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:layout_below="@id/pauseButton"
            android:layout_marginTop="16dp"
            android:layout_centerHorizontal="true"/>
    
        <!-- SeekBar for tracking progress -->
        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/stopButton"
            android:layout_marginTop="16dp"
            android:paddingHorizontal="16dp"
            android:max="100"/>
    
    </RelativeLayout>
    
    Login or Signup to reply.
  4. I’d like to help, I recently made a Database related apps : You can go through the code and understand pretty clearly:

    For studying Database in SQLite refer to the DatabaseHelper.java —

    This is an example of airline ticket reservation system

    BookingsActivity.java::

    package com.example.myapplication;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;
    
    
    public class BookingsActivity extends AppCompatActivity {
    
        private DatabaseHelper databaseHelper;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_bookings);
    
            databaseHelper = new DatabaseHelper(this);
    
            SQLiteDatabase db = databaseHelper.getReadableDatabase();
            Cursor cursor = db.query(DatabaseHelper.TABLE_BOOKINGS, null, null, null, null, null, null);
    
            StringBuilder pastBookings = new StringBuilder();
            while (cursor.moveToNext()) {
                pastBookings.append("Date: ").append(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_DATE)))
                        .append(", From: ").append(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_FROM)))
                        .append(", To: ").append(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TO)))
                        .append(", Airline: ").append(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_AIRLINE)))
                        .append("n");
            }
            cursor.close();
            db.close();
    
            TextView pastBookingsTextView = findViewById(R.id.pastBookingsTextView);
            pastBookingsTextView.setText(pastBookings.toString());
        }
    }
    

    MainActivity.java::

    package com.example.myapplication;
    
    import android.content.ContentValues;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;
    import android.widget.Toast;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    
    public class MainActivity extends AppCompatActivity {
    
        String[] airlines ={ "Air India", "Indigo", "Air Asia", "SpiceJet"};
        String[] places = { "Kolkata", "Mangalore", "Mumbai", "Chennai", "Delhi"};
        String[] passengerCounts = {"1", "2", "3", "4", "5"};
        String[] ticketClasses = {"Economy", "Business", "First Class"};
    
        private DatabaseHelper databaseHelper;
        String date;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            databaseHelper = new DatabaseHelper(this);
    
            Spinner fromSpinner = findViewById(R.id.fromSpinner);
            Spinner toSpinner = findViewById(R.id.toSpinner);
            Spinner airlineSpinner = findViewById(R.id.airlineSpinner);
            Spinner passengerSpinner = findViewById(R.id.passengerSpinner);
            Spinner classSpinner = findViewById(R.id.classSpinner);
    
            ArrayAdapter<String> placeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, places);
            ArrayAdapter<String> airlineAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, airlines);
            ArrayAdapter<String> passengerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, passengerCounts);
            ArrayAdapter<String> classAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, ticketClasses);
    
            fromSpinner.setAdapter(placeAdapter);
            toSpinner.setAdapter(placeAdapter);
            airlineSpinner.setAdapter(airlineAdapter);
            passengerSpinner.setAdapter(passengerAdapter);
            classSpinner.setAdapter(classAdapter);
    
            Button bookFlightButton = findViewById(R.id.bookFlightButton);
            bookFlightButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bookFlight();
                }
            });
        }
    
        private void bookFlight() {
            String date = this.date;
            String from = ((Spinner) findViewById(R.id.fromSpinner)).getSelectedItem().toString();
            String to = ((Spinner) findViewById(R.id.toSpinner)).getSelectedItem().toString();
            String airline = ((Spinner) findViewById(R.id.airlineSpinner)).getSelectedItem().toString();
            String passengers = ((Spinner) findViewById(R.id.passengerSpinner)).getSelectedItem().toString();
            String ticketClass = ((Spinner) findViewById(R.id.classSpinner)).getSelectedItem().toString();
    
            SQLiteDatabase db = databaseHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.COLUMN_DATE, date);
            values.put(DatabaseHelper.COLUMN_FROM, from);
            values.put(DatabaseHelper.COLUMN_TO, to);
            values.put(DatabaseHelper.COLUMN_AIRLINE, airline);
            values.put(DatabaseHelper.COLUMN_PASSENGERS, passengers);
            values.put(DatabaseHelper.COLUMN_CLASS, ticketClass);
    
            db.insert(DatabaseHelper.TABLE_BOOKINGS, null, values);
            db.close();
    
            Toast.makeText(this,"Booking successful!!",Toast.LENGTH_SHORT).show();
        }
    }
    

    DatabaseHelper.java:::

    package com.example.myapplication;
    
            import android.content.Context;
            import android.database.sqlite.SQLiteDatabase;
            import android.database.sqlite.SQLiteOpenHelper;
    
    public class DatabaseHelper extends SQLiteOpenHelper {
        static final String DATABASE_NAME = "airline_reservation.db";
        static final int DATABASE_VERSION = 1;
        static final String TABLE_BOOKINGS = "bookings";
        static final String COLUMN_ID = "id";
        static final String COLUMN_DATE = "date";
        static final String COLUMN_FROM = "from_location";
        static final String COLUMN_TO = "to_location";
        static final String COLUMN_AIRLINE = "airline";
        static final String COLUMN_PASSENGERS = "passengers";
        static final String COLUMN_CLASS = "class";
    
        // SQL statement to create the bookings table
        private static final String CREATE_TABLE_BOOKINGS = "CREATE TABLE " + TABLE_BOOKINGS +
                "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COLUMN_DATE + " TEXT," +
                COLUMN_FROM + " TEXT," +
                COLUMN_TO + " TEXT," +
                COLUMN_AIRLINE + " TEXT," +
                COLUMN_PASSENGERS + " TEXT," +
                COLUMN_CLASS + " TEXT" +
                ")";
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE_BOOKINGS);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKINGS);
    
            // Create tables again
            onCreate(db);
        }
    }
    

    activity_bookings.xml::

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        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"
        tools:context=".BookingsActivity">
    
        <TextView
            android:id="@+id/pastBookingsTextView"
            android:layout_width="378dp"
            android:layout_height="606dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    activity_main.xml::

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        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"
        tools:context=".BookingsActivity">
    
        <TextView
            android:id="@+id/pastBookingsTextView"
            android:layout_width="378dp"
            android:layout_height="606dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Also Don’t forget to use activity tag for Intent in the AndroidManifest.xml

    It should look something like this::

    <activity
                android:name=".BookingsActivity"
                android:exported="false" />
    

    If you need specifics feel free to ask, this is a very simple program which can help you learn the basics of DatabaseHelper.
    Have to code dump here as Android studio is notorious for the app crashing if there is even a small error and gradle issues can be overwhelming.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search