Android Studio:数据库搜索功能正常但无法通过按钮显示所有记录

Android Studio: Database search functions fine but unable to display all records via button

正如标题所说。我遵循了我的 class 教程,但似乎缺少了一些内容,当您不太精通此类内容时,视频讲座和 pdf 之间的切换有点令人困惑。

执行应用程序时,用户可以按年份搜索歌曲,或显示数据库中的所有记录。但是,最初单击按年份搜索按钮而不是显示所有按钮会显示所有记录。搜索功能按预期工作,但我似乎无法弄清楚显示所有按钮,尽管遵循了讲师的教程。

第一段代码是“MainActivity.java”,第二段代码是“OpenDatabse.java”

package com.example.dbcopyexample1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity
{
    private static String DATABASE_PATH_AND_NAME;
    private static String CHECK_DATABASES_FOLDER;

    //private static final String DATABASE_NAME = "music.db";
    private static final String LOG_TAG = "MUSIC_DB";

    Context ctx;

    OpenDatabase sqh;
    SQLiteDatabase sqdb;

    // Control Objects
    EditText searchByYearEditText;
    Button searchButton;
    TextView numRecordTextView;
    Button displayAllRecordsButton;
    TextView resultsTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupDatabaseStrings();
        setUpDatabase();

        InitDataBase(); // open the music.db for reading and writing

        //sqh.DisplayRecords( sqdb ); // Display the songtable records to the run window

        setupControls();

        numRecordTextView.setText( Integer.toString( sqh.numberOfRecordsInSongtable( sqdb ) ) );

    } //  protected void onCreate(Bundle savedInstanceState)

    protected void setupControls()
    {
        searchByYearEditText = findViewById(R.id.searchByYearEditText);

        searchButton = findViewById(R.id.searchButton);

        searchButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                resultsTextView.setText( sqh.searchByYearInSongtable( sqdb,
                        searchByYearEditText.getText().toString()) );


            }
        });

        numRecordTextView = findViewById(R.id.numRecordTextView);

        displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);

        displayAllRecordsButton.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View view)
            {

            }
        });

        resultsTextView = findViewById(R.id.resultsTextView);

    } // protected void setupControls()

    protected void setupDatabaseStrings()
    {
        // Full path to where we will copy music.db to on the emulator!
        DATABASE_PATH_AND_NAME = "/data/data/" + getApplicationContext().getPackageName() +
                "/databases/" + OpenDatabase.DATABASE_NAME;

        // Used to check if the "databases" folder exists
        CHECK_DATABASES_FOLDER = "/data/data/" + getApplicationContext().getPackageName() +
                "/databases";

        // Debug information
        Log.i("DATABASE_PATH_AND_NAME","DATABASE_PATH_AND_NAME = " + DATABASE_PATH_AND_NAME);
        Log.i("CHECK_DATABASES_FOLDER","CHECK_DATABASES_FOLDER = " + CHECK_DATABASES_FOLDER);

    } // protected void setupDatabaseStrings()

    protected void setUpDatabase()
    {
        ctx = this.getBaseContext();
        Log.w("CTX","ctx = " + ctx);
        Log.w("getBaseContext()","getBaseContext = " + getBaseContext());
        try
        {
            CopyDataBaseFromAsset();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    } // protected void setUpDatabase()

    protected void CopyDataBaseFromAsset() throws IOException
    {
        Log.w( LOG_TAG , "Starting copying...");

        String outputFileName = DATABASE_PATH_AND_NAME;

        File databaseFolder = new File( CHECK_DATABASES_FOLDER );

        // databases folder exists ? No - Create it and copy !!!
        if ( !databaseFolder.exists() )
        {
            databaseFolder.mkdir();

            // Open the sqlite database "music.db" found in the assets folder
            InputStream in = ctx.getAssets().open(OpenDatabase.DATABASE_NAME);

            OutputStream out = new FileOutputStream(outputFileName);

            byte[] buffer = new byte[1024];

            int length;

            while ( (length = in.read(buffer)) > 0 )
            {
                out.write(buffer,0,length);

            } // while ( (length = in.read(buffer)) > 0 )

            out.flush();
            out.close();
            in.close();

            Log.w(LOG_TAG, "Completed.");

        } // if ( !databaseFolder.exists() )

    } // protected void CopyDataBaseFromAsset() throws IOException

    public void InitDataBase()
    {
        // Init the SQLite Helper Class
        sqh = new OpenDatabase(this);

        // RETRIEVE A READABLE AND WRITEABLE DATABASE
        sqdb = sqh.getWritableDatabase();

    } // public void InitDataBase()

    public void DisplayRecords()
    {
        Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
        if (c != null)
        {
            if (c.moveToFirst())
            {
                do
                {
                    String id = c.getString(0);

                    String songtitle = c.getString(1);

                    String year = c.getString(2);

                    String artist = c.getString(3);

                    String album = c.getString(4);

                    Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);

                } while (c.moveToNext());
            }
        }
        c.close();

    } // public void DisplayRecords()


} // public class MainActivity extends AppCompatActivity
package com.example.dbcopyexample1;

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

import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class OpenDatabase extends SQLiteOpenHelper
{
    public static final String DATABASE_NAME = "music.db";

    // TOGGLE THIS NUMBER FOR UPDATING TABLES AND DATABASE
    private static final int DATABASE_VERSION = 1;

    OpenDatabase(Context context)
    {
        super( context, DATABASE_NAME, null, DATABASE_VERSION );

    } // OpenDatabase(Context context)

    @Override
    public void onCreate(SQLiteDatabase db)
    {

    } // public void onCreate(SQLiteDatabase db)

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {

    } // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

    public String searchByYearInSongtable(SQLiteDatabase sqdb, String searchYear)
    {
        String result = "";

        Cursor c = sqdb.rawQuery("SELECT * FROM songtable where year = '" + searchYear + "'",
                null);

        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    String id = c.getString(0);
                    result = result + id + ",";

                    String songtitle = c.getString(1);
                    result = result + songtitle + ",";

                    String year = c.getString(2);
                    result = result + year + ",";

                    String artist = c.getString(3);
                    result = result + artist + ",";

                    String album = c.getString(4);
                    result = result + album + "\n"; // new line control character

                    Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);

                } while (c.moveToNext());
            } else
            {
                result = "No Records Found for the Search Year = " + searchYear;
            }
        }
        c.close();

        return result;

    } // public String allRecordsInSongtable(SQLiteDatabase sqdb)

    public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
    {
        int count = 0;

        Cursor c = sqdb.rawQuery("SELECT count(*) FROM songtable", null);

        if (c != null)

        {
            if (c.moveToFirst())
            {
                do
                {
                    String id = c.getString(0);

                    count = Integer.parseInt( id );

                } while (c.moveToNext());
            }
        }
        c.close();
        return count;
    } // public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)

} // public class OpenDatabase extends SQLiteOpenHelper

您还没有调用 DisplayRecords() 函数在点击 displayAllRecordsButton 时显示记录。

displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);

displayAllRecordsButton.setOnClickListener(new View.OnClickListener()

{
    @Override
    public void onClick(View view)
    {
        DisplayRecords();
    }
});

另外,在DisplayRecords()方法中,您需要将文本设置为文本视图。 以下是我为显示记录而编辑的代码。

public void DisplayRecords()
{
    String result = "";
    Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
    if (c != null)
    {
        if (c.moveToFirst())
        {
            do
            {
                String id = c.getString(0);

                String songtitle = c.getString(1);

                String year = c.getString(2);

                String artist = c.getString(3);

                String album = c.getString(4);

                Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
                
                result = result + "ID = " + id + "Song Title = " + songtitle + "Artist = " + artist + "Album = " + album + "Year = " + year + "\n";

            } while (c.moveToNext());
        }
    }
    c.close();

    resultsTextView.setText(result);

} // public void DisplayRecords()