每日部落格

奶油冰激凌發表於2024-05-31

今天開發安卓端的科技政策一點通,相比於web端有點複雜,邊查資料邊敲程式碼一直弄到十一點。

部分程式碼

package com.example.policy;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.policy.utils.MySQLDatabaseHelper;

import java.util.List;

public class MainActivity1 extends AppCompatActivity {

    private RecyclerView recyclerView;
    private PolicyAdapter policyAdapter;
    private List<Policy> policyList;
    private EditText searchEditText;
    private MySQLDatabaseHelper databaseHelper;

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

        databaseHelper = new MySQLDatabaseHelper();

        recyclerView = findViewById(R.id.recyclerView);
        searchEditText = findViewById(R.id.searchEditText);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 從資料庫獲取政策資料
        policyList = databaseHelper.getAllPolicies();
        //UserDao userDao = new UserDao();
        //policyList= userDao.query2();
        policyAdapter = new PolicyAdapter(policyList);
        recyclerView.setAdapter(policyAdapter);

        searchEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 啟動 SearchActivity
                Intent intent = new Intent(MainActivity1.this, SearchActivity.class);
                String query = searchEditText.getText().toString();
                intent.putExtra("query", query);
                startActivity(intent);
            }
        });

        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                filterPolicies(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    private void filterPolicies(String query) {
        List<Policy> filteredPolicyList = databaseHelper.searchPolicies(query);
        policyAdapter.updateList(filteredPolicyList);
    }

}