代码之家  ›  专栏  ›  技术社区  ›  Hi Mr

如何在Android Studio中实现各种功能:Intents、AlertDialog、NotificationManager、MediaPlayer和SQLite数据库操作?

  •  -2
  • Hi Mr  · 技术社区  · 1 年前

    我正在Android Studio中开发一个Android应用程序,我需要帮助实现几个基本功能。具体而言,我需要以下方面的指导:

    使用意图在活动之间导航。 使用AlertDialog向用户显示消息。 使用NotificationManager发送通知。 实现用于音频播放的MediaPlayer。 使用DatabaseHelper类创建和管理SQLite数据库,包括表创建、插入值和基于条件获取数据。 我已经为每一个主题探索了文档和教程,但我很难将它们有效地集成到我的项目中。

    请有人提供全面的示例或代码片段,演示这些功能在Android Studio中的正确实现,无论是Java还是Kotlin?此外,如能深入了解最佳实践或避免常见陷阱,我们将不胜感激。

    我已经为每一个主题探索了文档和教程,但我很难将它们有效地集成到我的项目中。

    4 回复  |  直到 1 年前
        1
  •  1
  •   Hi Mr    1 年前

    另一个面向数据库的学生详细信息应用程序示例---

    主要活动.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("");
        }
    }
    

    数据库帮助程序.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_min.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>
    

    .

        2
  •  0
  •   Karthik Jangam    1 年前

    媒体播放器 主要活动.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>
    
        3
  •  -1
  •   Hi Mr    1 年前
    1. 数据库帮助程序示例--

      包com.example.l7q1;

      导入android.content。ContentValues; 导入android.content。上下文 导入android.database。光标; 导入android.database.sqlite。SQLiteDatabase; 导入android.database.sqlite。SQLiteOpenHelper;

      公共类DatabaseHelper扩展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. 弹出菜单示例--

    3. 带有微调器示例的第一页的基本布局--

      <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. 主要活动.java--

      导入android.os。捆 导入android.view。MenuItem; 导入android.view。看法 导入android.widget。阵列适配器; 导入android.widget。按钮 导入android.widget。弹出菜单; 导入android.widget。Spinner; 导入android.widget。面包

      导入androidx.appcompat.app。AppCompatActivity;

      导入java.util。ArrayList; 导入java.util。列表

      公共类MainActivity扩展了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();
      }
      

      }

        4
  •  -2
  •   Aayush Gupta    1 年前

    我想帮忙,我最近做了一个数据库相关的应用程序:你可以通过代码非常清楚地理解:

    要学习SQLite中的数据库,请参阅DatabaseHelper.java--

    这是机票预订系统的一个例子

    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版本=“1.0”编码=“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”
    工具:context=“.BookingsActivity”>
    
    <文本框
    android:id=“@+id/pastBookingsTextView”
    android:layout_width=“378dp”
    android:layout_height=“606dp”
    app:layout_constractBottom_toBottomOf=“父级”
    app:layout_contraintEnd_toEndOf=“父级”
    app:layout_contraintStart_toStartOf=“父级”
    app:layout_contraintTop_toTopOf=“父级”/>
    </androidx.constraintlayout.widget。约束布局>
    

    另外,不要忘记在AndroidManifest.xml中使用Intent的活动标记

    它应该是这样的:

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

    如果您需要详细信息,请随时询问,这是一个非常简单的程序,可以帮助您学习DatabaseHelper的基础知识。 必须在这里进行代码转储,因为安卓工作室因应用程序崩溃而臭名昭著,即使是一个小错误,等级问题也会非常严重。