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

วิธีเพิ่มข้อมูลจาก TreeMap ไปยัง ArrayList สำหรับ ListView ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการใช้ TreeMap ร่วมกับ ArrayList และ ListView ใน Android พร้อมฟังก์ชัน เพิ่ม และรีเฟรช ข้อมูล โดย TreeMap จะ จัดเรียง Key อัตโนมัติตามลำดับธรรมชาติ (Natural Order)

ขั้นตอนที่ 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/record"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="record number"
        android:inputType="number" />

    <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" />

    </LinearLayout>

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

</LinearLayout>

ในโค้ดข้างต้น เรามีช่องกรอก "record number" (Key) และ "Name" (Value) พร้อมปุ่ม Save, Refresh และ 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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

public class MainActivity extends AppCompatActivity {

    Button save, refresh;
    EditText name, record;
    ArrayAdapter<String> arrayAdapter;
    ArrayList<String> arrayList;
    Map<String, String> map = new TreeMap<>();
    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);
        record = findViewById(R.id.record);
        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();
                }
            }
        });

        // ปุ่ม Save - เพิ่มข้อมูลลง TreeMap
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nameText = name.getText().toString().trim();
                String recordText = record.getText().toString().trim();

                if (!nameText.isEmpty() && !recordText.isEmpty()) {
                    // เพิ่มใน TreeMap (Key จะถูกจัดเรียงอัตโนมัติ)
                    map.put(recordText, nameText);
                    
                    // อัปเดต ListView
                    updateListView();
                    
                    Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
                } else {
                    if (nameText.isEmpty()) name.setError("Enter NAME");
                    if (recordText.isEmpty()) record.setError("Enter Record");
                }
            }
        });
    }

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

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

  • TreeMap - Map ที่ จัดเรียง Key อัตโนมัติ ตามลำดับธรรมชาติ (Natural Ordering) - สำหรับ String จะเป็นลำดับตัวอักษร, สำหรับ Number จะเป็นลำดับตัวเลข
  • map.put(key, value) - เพิ่ม/อัปเดตข้อมูล Key จะถูกจัดเรียงทันที
  • map.values() - ดึงค่าทั้งหมดตามลำดับ Key ที่จัดเรียงแล้ว
  • ไม่มีปุ่ม Delete ในตัวอย่างนี้ (มีแค่ Save และ Refresh)
💡 เปรียบเทียบ Map ใน Java:
• HashMap - ไม่จัดเรียง, เร็วที่สุด O(1), อนุญาต null key/value
• LinkedHashMap - รักษาลำดับการเพิ่ม, เร็ว O(1)
• TreeMap - จัดเรียง Key อัตโนมัติ, ช้ากว่า O(log n), ไม่อนุญาต null key
การปรับปรุงจากโค้ดต้นฉบับ:
• เพิ่ม Generic Types: Map<String, String>, TreeMap<>, ArrayAdapter<String>
• สร้างเมธอด updateListView() แยกต่างหาก
• ใช้ trim() และตรวจสอบ empty อย่างถูกต้อง
• ลบ import ที่ไม่ใช้งาน (Button ไม่ได้ใช้โดยตรง)

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

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

วิธีเพิ่มข้อมูลจาก TreeMap ไปยัง ArrayList สำหรับ ListView ใน Android

ภาพ: เพิ่มชื่อจาก TreeMap ไปยัง ArrayList แสดงใน ListView (จัดเรียงตาม record number)