You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Firebase获取的医疗诊所信息改为下拉框选择并跳转评价页?

Hey there! Let's convert your existing ListView-based clinic picker into a Spinner that lets users select a clinic and jump straight to the review-writing step. Here's a step-by-step breakdown of how to make this happen:

1. Update Your Layout File (activity_list_view.xml)

First, swap out the ListView with a Spinner in your layout. You can keep the EditText if you want to add search functionality later, or remove it if it's not needed:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <!-- Optional: Keep for search functionality -->
    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search for a clinic..." />

    <!-- Replace ListView with Spinner -->
    <Spinner
        android:id="@+id/clinic_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp" />

</LinearLayout>

2. Rewrite the Activity Code (ListViewActivity.java)

We'll replace the ListView logic with Spinner handling, store full clinic objects instead of just strings, and add a selection listener to launch the review activity:

public class ListViewActivity extends AppCompatActivity {
    private Spinner clinicSpinner;
    private EditText editSearch;
    private ArrayList<Information> clinicList;
    private ClinicAdapter clinicAdapter;

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

        // Initialize views
        clinicSpinner = findViewById(R.id.clinic_spinner);
        editSearch = findViewById(R.id.edit);

        // Store full clinic data instead of just formatted strings
        clinicList = new ArrayList<>();
        clinicAdapter = new ClinicAdapter(this, clinicList);
        clinicSpinner.setAdapter(clinicAdapter);

        // Fetch clinics from Firebase
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Medical Clinic");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                clinicList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Information info = snapshot.getValue(Information.class);
                    if (info != null) {
                        // Save the Firebase key to link reviews to this clinic later
                        info.setClinicId(snapshot.getKey());
                        clinicList.add(info);
                    }
                }
                clinicAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(ListViewActivity.this, "Failed to load clinics: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        // Handle Spinner selection
        clinicSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Information selectedClinic = clinicList.get(position);
                // Launch review activity and pass clinic details
                Intent intent = new Intent(ListViewActivity.this, ReviewWritingActivity.class);
                intent.putExtra("CLINIC_ID", selectedClinic.getClinicId());
                intent.putExtra("CLINIC_NAME", selectedClinic.getName());
                startActivity(intent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Optional: Show a prompt to select a clinic
            }
        });
    }

    // Custom adapter to display clinic details in the Spinner
    private static class ClinicAdapter extends ArrayAdapter<Information> {
        public ClinicAdapter(Context context, ArrayList<Information> clinics) {
            super(context, 0, clinics);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return buildClinicView(position, convertView, parent);
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return buildClinicView(position, convertView, parent);
        }

        private View buildClinicView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
            }

            Information clinic = getItem(position);
            if (clinic != null) {
                TextView clinicDetails = convertView.findViewById(R.id.clinic_details_text);
                String displayText = clinic.getName() + " : " + clinic.getAddress() + " : " + clinic.getPhone_No() + " : " + clinic.getPostcode();
                clinicDetails.setText(displayText);
            }

            return convertView;
        }
    }
}

3. Update Your Information Class

Add a field to store the Firebase clinic ID (critical for linking reviews to the correct clinic later):

public class Information {
    private String name;
    private String address;
    private String phone_No;
    private String postcode;
    private String clinicId; // New field for Firebase key

    // Default constructor required for Firebase deserialization
    public Information() {}

    // Getters and setters for all fields
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }

    public String getPhone_No() { return phone_No; }
    public void setPhone_No(String phone_No) { this.phone_No = phone_No; }

    public String getPostcode() { return postcode; }
    public void setPostcode(String postcode) { this.postcode = postcode; }

    public String getClinicId() { return clinicId; }
    public void setClinicId(String clinicId) { this.clinicId = clinicId; }
}

4. Create the Review Writing Activity

Make a new activity where users can submit reviews. Here's a basic implementation:

public class ReviewWritingActivity extends AppCompatActivity {
    private EditText editReview;
    private Button submitBtn;
    private String clinicId;

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

        editReview = findViewById(R.id.edit_review);
        submitBtn = findViewById(R.id.submit_review_btn);

        // Get clinic data from the intent
        Intent intent = getIntent();
        clinicId = intent.getStringExtra("CLINIC_ID");
        String clinicName = intent.getStringExtra("CLINIC_NAME");
        setTitle("Write a Review for " + clinicName);

        // Handle review submission
        submitBtn.setOnClickListener(v -> {
            String reviewText = editReview.getText().toString().trim();
            if (!reviewText.isEmpty()) {
                // Save review to Firebase under the selected clinic's ID
                DatabaseReference reviewRef = FirebaseDatabase.getInstance().getReference("Reviews").child(clinicId).push();
                Review newReview = new Review(reviewText, FirebaseAuth.getInstance().getCurrentUser().getUid(), System.currentTimeMillis());
                
                reviewRef.setValue(newReview)
                        .addOnSuccessListener(aVoid -> {
                            Toast.makeText(this, "Review submitted successfully!", Toast.LENGTH_SHORT).show();
                            finish();
                        })
                        .addOnFailureListener(e -> {
                            Toast.makeText(this, "Failed to submit review: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
            } else {
                Toast.makeText(this, "Please enter a review first!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

// Review model class
class Review {
    private String text;
    private String userId;
    private long timestamp;

    public Review() {}

    public Review(String text, String userId, long timestamp) {
        this.text = text;
        this.userId = userId;
        this.timestamp = timestamp;
    }

    // Getters and setters
    public String getText() { return text; }
    public void setText(String text) { this.text = text; }

    public String getUserId() { return userId; }
    public void setUserId(String userId) { this.userId = userId; }

    public long getTimestamp() { return timestamp; }
    public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
}

Quick Notes:

  • Custom Adapter: Using a custom adapter lets us keep the full clinic object, making it easy to pass data to the review activity.
  • Firebase Key: Storing the clinic's Firebase key ensures reviews are linked to the correct clinic.
  • Error Handling: Added basic error messages to keep users informed if something goes wrong.

内容的提问来源于stack exchange,提问作者user14334679

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:32:35