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

ที่ไหนและอย่างไรที่จะใช้ตัวแปร Static ใน Android Studio

การใช้งานตัวแปร Static ใน Android: ตัวอย่างและ Best Practices

ตัวอย่างนี้แสดงการใช้ static final สำหรับค่าคงที่ (Constant) เช่น TAG สำหรับ Logging และอธิบายเมื่อไหร่ควร/ไม่ควรใช้ Static Variable

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

Android Studio → File → New Project → กรอกรายละเอียด → Finish

ขั้นตอนที่ 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:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">
    <TextView
        android:id="@+id/Question"
        android:layout_width="wrap_content"
        android:layout_height="93dp"
        android:padding="8dp"
        android:text="I'm a Static Variable"
        android:layout_marginTop="32sp"
        android:layout_marginLeft="8dp"
        android:textSize="32dp"
        tools:layout_editor_absoluteY="8dp" />
</LinearLayout>

ขั้นตอนที่ 3: MainActivity.java

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    // Static Final Constant - ใช้สำหรับ TAG Logging
    public static final String TAG = "Have a nice day!";

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

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop");
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

เมื่อไหร่ควรใช้ Static Variable

⚠️ อันตรายของ Static Variable ใน Android

  1. Memory Leak - Static variable ค้างอยู่จน Process จบ ถ้ามี Context/View จะไม่ให้ GC ทำงาน
  2. Thread Safety - Static เข้าถึงได้จากทุก Thread ต้อง Synchronize
  3. Testability - ยากต่อการ Unit Test (Mock ไม่ได้ง่าย)
  4. Process Death - Android อาจ Kill Process แล้วสร้างใหม่ Static จะ Reset

Best Practices

// ✅ ดี: Constants
public static final String PREF_NAME = "my_prefs";
public static final int DEFAULT_TIMEOUT = 5000;

// ✅ ดี: Utility Class (final class, private constructor)
public final class DateUtils {
    private DateUtils() {} // ป้องกัน Instantiation
    public static String format(Date date) { ... }
}

// ✅ ดี: Singleton ด้วย Enum (Thread-safe)
public enum AppRepository {
    INSTANCE;
    private Database db;
    public Database getDb() { return db; }
}

// ❌ ไม่ดี: Static Context/View
public class MyActivity extends Activity {
    static TextView textView; // LEAK!
    static Context context;   // LEAK!
}

การใช้ Static สำหรับ Logging (เหมือนตัวอย่าง)

// ดี - ใช้ static final สำหรับ TAG
public class MyActivity extends AppCompatActivity {
    private static final String TAG = MyActivity.class.getSimpleName();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate"); // ใช้ TAG คงที่
    }
}

สรุป

  • ใช้ static final สำหรับ Constants (TAG, Keys, Config)
  • ใช้ Static Methods สำหรับ Utility Functions
  • ห้าม เก็บ Context, View, Activity, Fragment ใน Static Variable
  • ใช้ Singleton Pattern อย่างระมัดระวัง (ควรใช้ Dependency Injection/Hilt แทน)
กรณีเหมาะสม?ตัวอย่าง
Constants (ค่าคงที่)✅ ใช่static final String TAG = "MyApp"; static final int MAX_SIZE = 100;
Utility Methods✅ ใช่static String formatDate(Date d) { ... }
Singleton Pattern⚠️ ระวังstatic InstanceHolder { static final MyClass INSTANCE = new MyClass(); }
Shared State ระหว่าง Instance❌ หลีกเลี่ยงstatic User currentUser; // Memory Leak, Thread Safety
Context/View References❌ ห้ามstatic Context context; // Memory Leak แน่นอน