Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีลบข้อมูลจาก HashSet ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการใช้ HashSet ร่วมกับ ArrayList และ ListView ใน Android พร้อมฟังก์ชัน เพิ่ม ลบ และรีเฟรช ข้อมูล โดย HashSet จะเก็บข้อมูล ไม่ซ้ำกัน (Unique) และ ไม่รักษาลำดับ

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save" />

        <Button
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Refresh" />

        <Button
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

ในโค้ดข้างต้น เรามีช่องกรอก "Name" พร้อมปุ่ม Save, Refresh, Delete และ ListView แสดงผล

ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    EditText name;
    ArrayAdapter<String> arrayAdapter;
    ArrayList<String> arrayList;
    Set<String> set = new HashSet<>();
    private ListView listView;

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

        arrayList = new ArrayList<>();
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

        // ปุ่ม Refresh - อัปเดตการแสดงผล
        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (arrayAdapter != null) {
                    arrayAdapter.notifyDataSetChanged();
                    listView.invalidateViews();
                    listView.refreshDrawableState();
                }
            }
        });

        // ปุ่ม Delete - ลบข้อมูลตามชื่อ
        findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nameText = name.getText().toString().trim();
                if (!nameText.isEmpty()) {
                    // ลบจาก HashSet
                    set.remove(nameText);
                    
                    // อัปเดต ListView
                    updateListView();
                    
                    Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show();
                } else {
                    name.setError("Enter NAME");
                }
            }
        });

        // ปุ่ม Save - เพิ่มข้อมูล
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nameText = name.getText().toString().trim();
                if (!nameText.isEmpty()) {
                    // เพิ่มใน HashSet (ไม่ซ้ำ ไม่รักษาลำดับ)
                    set.add(nameText);
                    
                    // อัปเดต ListView
                    updateListView();
                    
                    Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
                } else {
                    name.setError("Enter NAME");
                }
            }
        });
    }

    // เมธอดช่วยอัปเดต ListView
    private void updateListView() {
        arrayList.clear();
        arrayList.addAll(set);
        
        arrayAdapter = new ArrayAdapter<>(
            MainActivity.this,
            android.R.layout.simple_list_item_1,
            arrayList
        );
        listView.setAdapter(arrayAdapter);
    }
}

คำอธิบายสำคัญ:

  • HashSet - ชุดข้อมูลที่ ไม่ซ้ำกัน (Unique) และ ไม่รักษาลำดับการเพิ่ม ใช้ Hash Table ทำงานเร็วที่สุดในกลุ่ม Set
  • set.add() - เพิ่มข้อมูล (ถ้ามีอยู่แล้วจะไม่เพิ่มซ้ำ คืนค่า false)
  • set.remove() - ลบข้อมูลตามค่าที่ระบุ (คืนค่า true ถ้าลบสำเร็จ)
  • ลำดับใน ListView อาจเปลี่ยนไปทุกครั้งที่ Refresh เนื่องจาก HashSet ไม่รักษาลำดับ
💡 เปรียบเทียบ Set ใน Java (สรุป):
• HashSet - ไม่ซ้ำ, ไม่รักษาลำดับ, เร็วที่สุด O(1)
• LinkedHashSet - ไม่ซ้ำ, รักษาลำดับการเพิ่ม, เร็ว O(1)
• TreeSet - ไม่ซ้ำ, จัดเรียงตามลำดับธรรมชาติ, ช้ากว่า O(log n)
การปรับปรุงจากโค้ดต้นฉบับ:
• เพิ่ม Generic Types: Set<String>, HashSet<String>, ArrayAdapter<String>
• สร้างเมธอด updateListView() แยกต่างหาก
• ใช้ trim() และตรวจสอบ empty อย่างถูกต้อง
• แก้ไขคำอธิบายใน Layout (ต้นฉบับกล่าวถึง record number แต่ Layout ไม่มี)

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ

วิธีลบข้อมูลจาก HashSet ใน Android

วิธีลบข้อมูลจาก HashSet ใน Android

ภาพ: เพิ่มข้อมูล 2 รายการ แสดงใน ListView (ลำดับอาจสุ่ม)

วิธีลบข้อมูลจาก HashSet ใน Android

ภาพ: กด Delete แล้วรายการถูกลบออกจาก ListView