如何在 Android Studio 中使用按钮按初始筛选并使用 SQLite 将其显示在另一个活动上

Posted

技术标签:

【中文标题】如何在 Android Studio 中使用按钮按初始筛选并使用 SQLite 将其显示在另一个活动上【英文标题】:How to filter by initial using a button and display it on another activity using SQLite in Android Studio 【发布时间】:2021-07-20 03:04:16 【问题描述】:

我正在 android studio 中创建一个访客管理系统应用程序。我有一个 SQLite 数据库,可以在其中存储、添加、删除和查看记录。我现在想使用另一个带有字母 A-Z 的 Activity 作为按钮来点击诸如“A 按钮”之类的按钮,它将带我进入一个新的 Activity 并显示名称以 A 开头的每个用户。

我已经搜索了好几个小时试图找到并弄清楚但什么都找不到。

数据库助手在这里:

public class DatabaseHelper extends SQLiteOpenHelper 

    public static final String USER_TABLE = "USER_TABLE";
    public static final String COLUMN_USER_NAME = "USER_NAME";
    public static final String COLUMN_SINGED_IN = "SINGED_IN";
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_STAFF_VISITOR = "STAFF_VISITOR";    
    public DatabaseHelper(@Nullable Context context) 
        super(context, "user.db", null, 1);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        String createTableStatement = "CREATE TABLE " + USER_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_USER_NAME + " TEXT, " + COLUMN_STAFF_VISITOR + " TEXT, " + COLUMN_SINGED_IN + " BOOL )";  
        db.execSQL(createTableStatement);  
    

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

    public boolean addOne(UserModel userModel)    
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();  
        cv.put(COLUMN_USER_NAME, userModel.getName());
        cv.put(COLUMN_STAFF_VISITOR, userModel.getStaff_visitor());
        cv.put(COLUMN_SINGED_IN, userModel.isOnSite());  
        long insert = db.insert(USER_TABLE, null, cv);
        if( insert == -1)
            return false;
        
        else 
            return true;
        
    

    public List<UserModel> getallUsers()

        List<UserModel> returnList = new ArrayList<>();
        String queryString = "SELECT * FROM " + USER_TABLE;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(queryString, null);

        if(cursor.moveToFirst())
            //Go through the results (loop). Insert them into a return list to display.
            do
                int userID = cursor.getInt(0);
                String userName = cursor.getString(1);
                String staffVisitor = cursor.getString(2);
                boolean signedIn = cursor.getInt(3) == 1? true: false;

                UserModel newUser = new UserModel(userID, userName, staffVisitor, signedIn);
                returnList.add(newUser);

            while (cursor.moveToNext());
        
        else 
            //Fail - do not add to list.   
        
        cursor.close();
        db.close();
        return returnList;
    

    public boolean deleteOne(UserModel userModel)
        SQLiteDatabase db = this.getWritableDatabase();
        String queryString = " DELETE FROM " + USER_TABLE + " WHERE " + COLUMN_ID + " = " + 
        userModel.getId();

        Cursor cursor = db.rawQuery(queryString, null);

        if(cursor.moveToFirst())
            cursor.close();
            return  true;
        
        else 
            cursor.close();
            return false;
        
    

    public List<UserModel> getSpecificUser()

        List<UserModel> returnList = new ArrayList<>();
        String queryString = "SELECT * FROM " + USER_TABLE + " WHERE " + COLUMN_USER_NAME + " = " + "[]";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(queryString, null);

        if(cursor.moveToFirst())
            //Go through the results (loop). Insert them into a return list to display.
            do
                int userID = cursor.getInt(0);
                String userName = cursor.getString(1);
                String staffVisitor = cursor.getString(2);
                boolean signedIn = cursor.getInt(3) == 1? true: false;

                UserModel newUser = new UserModel(userID, userName, staffVisitor, signedIn);
                returnList.add(newUser);

            while (cursor.moveToNext());
        
        else 
            //Fail - do not add to list.
        
        cursor.close();
        db.close();
        return returnList;
    

这与管理屏幕一起用于添加、删除和查看所有记录。

我现在需要这个数据库来处理我的员工选择屏幕。这是:

public class Staff_Selection extends Activity implements View.OnClickListener 

    Button btn_home;
    DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.staff_selection);
        databaseHelper = new DatabaseHelper(Staff_Selection.this);

        btn_home = findViewById(R.id.home_4);
        Button a = findViewById(R.id.btnAv);
        a.setOnClickListener(this);
        Button b = findViewById(R.id.btnBv);
        b.setOnClickListener(this);
        Button c = findViewById(R.id.btnCv);
        c.setOnClickListener(this);
        Button d = findViewById(R.id.btnDv);
        d.setOnClickListener(this);
        Button e = findViewById(R.id.btnEv);
        e.setOnClickListener(this);
        Button f = findViewById(R.id.btnFv);
        f.setOnClickListener(this);
        Button g = findViewById(R.id.btnGv);
        g.setOnClickListener(this);
        Button h = findViewById(R.id.btnHv);
        h.setOnClickListener(this);
        Button i = findViewById(R.id.btnIv);
        i.setOnClickListener(this);
        Button j = findViewById(R.id.btnJv);
        j.setOnClickListener(this);
        Button k = findViewById(R.id.btnKv);
        k.setOnClickListener(this);
        Button l = findViewById(R.id.btnLv);
        l.setOnClickListener(this);
        Button m = findViewById(R.id.btnMv);
        m.setOnClickListener(this);
        Button n = findViewById(R.id.btnNv);
        n.setOnClickListener(this);
        Button o = findViewById(R.id.btnOv);
        o.setOnClickListener(this);
        Button p = findViewById(R.id.btnPv);
        p.setOnClickListener(this);
        Button q = findViewById(R.id.btnQv);
        q.setOnClickListener(this);
        Button r = findViewById(R.id.btnRv);
        r.setOnClickListener(this);
        Button s = findViewById(R.id.btnSv);
        s.setOnClickListener(this);
        Button t = findViewById(R.id.btnTv);
        t.setOnClickListener(this);
        Button u = findViewById(R.id.btnUv);
        u.setOnClickListener(this);
        Button v = findViewById(R.id.btnVv);
        v.setOnClickListener(this);
        Button w = findViewById(R.id.btnWv);
        w.setOnClickListener(this);
        Button x = findViewById(R.id.btnXv);
        x.setOnClickListener(this);
        Button y = findViewById(R.id.btnYv);
        y.setOnClickListener(this);
        Button z = (Button) findViewById(R.id.btnZv);
        z.setOnClickListener(this);    
    
        btn_home.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                openActivityHome();
                finish();
            

        );
    

    public void openActivityHome() 

        Intent intent = new Intent(this, Initial_Screen.class);
        startActivity(intent);
    


    @Override
    public void onClick(View v) 
        switch (v.getId()) 

            case R.id.btnAv:
                DatabaseHelper databaseHelper = new DatabaseHelper(Staff_Selection.this);
                List<UserModel> allUsers = databaseHelper.getSpecificUser();

                ShowUsersonListView(databaseHelper);
                break;
            case R.id.btnBv:
                break;
            case R.id.btnCv:
                break;
            case R.id.btnDv:
                break;
            case R.id.btnEv:
                break;
            case R.id.btnFv:
                break;
            case R.id.btnGv:
                break;
            case R.id.btnHv:
                break;
            case R.id.btnIv:
                break;
            case R.id.btnJv:
                break;
            case R.id.btnKv:
                break;
            case R.id.btnLv:
                break;
            case R.id.btnMv:
                break;
            case R.id.btnNv:
                break;
            case R.id.btnOv:
                break;
            case R.id.btnPv:
                break;
            case R.id.btnQv:
                break;
            case R.id.btnRv:
                break;
            case R.id.btnSv:
                break;
            case R.id.btnTv:
                break;
            case R.id.btnUv:
                break;
            case R.id.btnVv:
                break;
            case R.id.btnWv:
                break;
            case R.id.btnXv:
                break;
            case R.id.btnYv:
                break;
            case R.id.btnZv:
                break;
            default:
                break;
        
    
    private void ShowUsersonListView(DatabaseHelper databaseHelper) 
    

然后在此屏幕上按下的按钮应更新或显示列表视图或结果列表,具体取决于选择到此屏幕的字母。

public class Name_Display_Staff extends AppCompatActivity 
    Button btn_home;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.name_display);
        btn_home = findViewById(R.id.home_1);
        btn_home.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                openActivityHome();
                finish();
            
        );
    

    public void openActivityHome() 
        Intent intent = new Intent(this, Initial_Screen.class);
        startActivity(intent);
    

任何帮助的想法都会很棒,甚至可以提供帮助的文档或视频。

【问题讨论】:

【参考方案1】:

也许考虑以下基于您的代码但有很多更改的内容。

MainActivity 相当于您的 Staff_Selection(26 个字母按钮)和 Activity2 相当于你name_Display_Staff(获取传递的数据)

MainActivity 相当长,可能容易出现维护问题。很多 MainActivity 已被重写以处理按钮,方法是根据保存按钮字母的 String[] 动态添加按钮。

已添加所选用户的 ListView,单击列表中的用户会将您带到第二个活动 Activity2,这是非常基本的,因为它只是获取 UserModel 并将详细信息写入日志。

列表视图使用 CursorAdapter,即 SimpleCursorAdapter,它是为使用 Cursors 而设计的。

MainActivity 使用的布局要简单得多,因为没有定义按钮。对于示例/演示/建议,使用的布局是:-

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MainActivity"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/buttonlist"
        android:layout_
        android:layout_
        android:orientation="horizontal">
    </LinearLayout>

    <ListView
        android:id="@+id/userlist"
        android:layout_
        android:layout_>
    </ListView>
</LinearLayout>
即只有 2 个视图,一个用于按钮的 LinearLayout 和一个用于 UserModel 列表的 ListView。 请注意,此布局仅用于演示。

DatabaseHelper 已被 a) 修改为数据库添加一个类变量(您真的不想打开和关闭数据库):-

public static final String COLUMN_STAFF_VISITOR = "STAFF_VISITOR";
SQLiteDatabase db; //<<<<<<<<<< ADDED

b)添加以下2个方法

:-

//* ADDED *//
public UserModel getUserById(long id) 
    UserModel rv = null;
    Cursor csr = db.query(USER_TABLE,null,COLUMN_ID+"=?",new String[]String.valueOf(id),null,null,null);
    if (csr.moveToFirst()) 
        rv = new UserModel(
                csr.getLong(csr.getColumnIndex(COLUMN_ID)),
                csr.getString(csr.getColumnIndex(COLUMN_USER_NAME)),
                csr.getString(csr.getColumnIndex(COLUMN_STAFF_VISITOR)),
                csr.getInt(csr.getColumnIndex(COLUMN_SINGED_IN))>0
        );
    
    csr.close();
    return rv;


// ADDED //
public Cursor getUsersByFirstLetter(String firstLetter) 
    return db.query(USER_TABLE,
            new String[]
                    COLUMN_ID + " AS " + BaseColumns._ID,
                    COLUMN_USER_NAME,
                    COLUMN_STAFF_VISITOR,
                    COLUMN_SINGED_IN
            ,
            COLUMN_USER_NAME + " LIKE ?",
            new String[]firstLetter + "%",
            null,null,COLUMN_USER_NAME + " ASC",null);

getUserById 只允许将 ID 从 MainActivity 传递到 Activity2 **getUserByFirstletter 根据传递的字母返回基于行的游标,例如使用 getUserByFirstLetter("A") 调用它会获取用户名以 A 开头的所有行(传递 "" 获取所有行)。

否则DatabaseHelper是原样(您可能需要考虑根据上述方法更改它。)

活动2

这是一个非常基本的活动,旨在展示获取适当 UserModel 的原理。它不利于返回(例如完成 Activity 按钮)。

调用时,它只是从数据库中获取 UserModel 并将详细信息写入日志。

public class Activity2 extends AppCompatActivity 

    DatabaseHelper databaseHelper;
    public final static String MYINTENET_USERID = "ACTIVITY2_USERID";
    UserModel um;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        databaseHelper = new DatabaseHelper(this);
        um = getuserModel(this.getIntent().getLongExtra(MYINTENET_USERID,-1)); //<<<<<<<<<< gets the UserModel based upon the id passed via the Intent.
        Log.d("USERMODELINFO","User is " + um.getName() + " staff_visitor is " + um.getStaff_visitor() + " onsite = " + um.isOnSite() + " ID = " + um.getId());
    

    private UserModel getuserModel(long id) 
        return databaseHelper.getUserById(id);
    

MainActivity

如前所述,这是完全不同的:-

按钮是基于常量 ALPHABET 动态添加到其他空的 LinearLayout 的,ID 为 buttonlist(请注意如何添加 $ 以显示灵活性)。按钮的属性是最小的。但是,所选按钮的背景与其他按钮形成鲜明对比。

在演示中并非所有按钮都出现(您需要更改)

一个 SimpleCursorAdapter 用于 ListView。

我添加了一种方法来添加一些数据,以便演示中显示一些内容。

:-

public class MainActivity extends AppCompatActivity 

    public  static final String[] ALPHABET = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z,$";
    private Button[] buttons = new Button[ALPHABET.length];
    LinearLayout buttonList;
    ListView userList;
    Cursor users;
    SimpleCursorAdapter sca;
    DatabaseHelper databaseHelper;
    int buttonBckgrndNormal = 0xFFFFFFFF;
    int buttonBckgrndSelected = 0xFFFF0000;
    int buttonTextColour = 0xFF000000;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseHelper = new DatabaseHelper(this);
        forTestingAddSomeData();

        buttonList = this.findViewById(R.id.buttonlist);
        userList = this.findViewById(R.id.userlist);
        // Add buttons for Letters of the Alphabet
        for(int i = 0;i < ALPHABET.length;i++) 
            addAButton(i);
        
        setOrResetCursorAdapter("");
    

    //* Setup the List View */
    private void setOrResetCursorAdapter(String firstLetter) 
        users = databaseHelper.getUsersByFirstLetter(firstLetter);
        Toast.makeText(this,"retrieved " + users.getCount() + " rows from database.",Toast.LENGTH_SHORT).show();
        if (sca == null) 
            sca = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    users,
                    new String[]
                            DatabaseHelper.COLUMN_USER_NAME,
                            DatabaseHelper.COLUMN_STAFF_VISITOR,
                    new int[]
                    android.R.id.text1, android.R.id.text2
                            ,0);
            userList.setAdapter(sca);
            userList.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
                    intent = new Intent(MainActivity.this,Activity2.class);
                    intent.putExtra(Activity2.MYINTENET_USERID,l);
                    startActivity(intent);
                
            );
         else 
            sca.swapCursor(users);
        
    

    //* Add a button dynamically */
    private Button addAButton(int i) 
        buttons[i] = new Button(this);
        buttons[i].setBackgroundColor(buttonBckgrndNormal);
        buttons[i].setText(ALPHABET[i]);
        buttons[i].setTextColor(buttonTextColour);
        buttons[i].setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                buttonReset();
                view.setBackgroundColor(buttonBckgrndSelected);
                setOrResetCursorAdapter(((Button)view).getText().toString());
            
        );
        buttonList.addView(buttons[i]);
        return buttons[i];
    

    /* Reset ALL buttons as not selected */
    private void buttonReset() 
        for(int i=0; i < buttonList.getChildCount();i++) 
            buttonList.getChildAt(i).setBackgroundColor(buttonBckgrndNormal);
        
    

    private void forTestingAddSomeData() 
        UserModel[] umList = new UserModel[] 
                new UserModel(1,"Fred","Harriet",false),
                new UserModel(2,"Mary","Sarah",false),
                new UserModel(1,"Annabel","Zed",false),
                new UserModel(1,"Bob","Claire",true)
        ;
        for(UserModel u: umList) 
            databaseHelper.addOne(u);
        
    

结果

应用程序启动时(首次运行时)是:-

点击A按钮和:-

只显示 Annabel

的第一行

点击F :-

点击列表中的 Fred :-

带你到Activity2(空显示),日志包括:-

D/USERMODELINFO: User is Fred staff_visitor is Harriet onsite = false ID = 1

【讨论】:

感谢您的帮助!很抱歉,对此很陌生,并且已经陷入困境。

以上是关于如何在 Android Studio 中使用按钮按初始筛选并使用 SQLite 将其显示在另一个活动上的主要内容,如果未能解决你的问题,请参考以下文章

请问android studio如何通过代码获得不同时区的时间,比如界面按一下美国的按钮,显示的就是美国的时间

Android Studio片段没有响应后按按钮

如何在android studio中启用设备框架?

Android Studio:按几个按钮

如何使用 DatePicker 和 TimePicker (Android Studio) 在数据库中存储日期和时间?

如何在 Android Studio 中查找使当前打开的布局文件膨胀的 Activity 或 Fragment