如何在 Android 中使用全域性上下文儲存 JSON 物件單例?
在進入示例之前,我們應該瞭解單例設計模式是什麼。單例是一種設計模式,它將類的例項化限制為只有一個例項。值得注意的用途包括控制併發和建立應用程式訪問其資料儲存的中心訪問點。
此示例演示如何在 Android 中使用全域性上下文儲存 JSON 物件單例
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/show" android:text = "save json in singleTone" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,我們添加了一個按鈕。當用戶點選“顯示”按鈕時,它將在吐司中顯示 JSON 物件。
步驟 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.Button; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { Button show; JSONObject jsonObject; singleTonExample singletonexample; { try { jsonObject = new JSONObject("{\"balance\": 1000.21, \"num\":100, \"is_vip\":true, \"name\":\"foo\"}"); } catch (JSONException e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); singletonexample = singleTonExample.getInstance(); singletonexample.init(getApplicationContext()); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { singletonexample.storeJson(jsonObject); Toast.makeText(singleTonExample.get(), singletonexample.getJSON(), Toast.LENGTH_LONG).show(); } }); } }
在上面的程式碼中,我們使用了 singleTonExample 作為單例類,因此建立一個名為 singleTonExample.java 的呼叫並新增以下程式碼 -
package com.example.andy.myapplication; import android.app.Dialog; import android.content.Context; import android.view.Window; import org.json.JSONObject; import java.util.Arrays; public class singleTonExample { private Context appContext; JSONObject i1; private static final singleTonExample ourInstance = new singleTonExample(); public void init(Context context) { if(appContext = = null) { this.appContext = context; } } private Context getContext() { return appContext; } public static Context get() { return getInstance().getContext(); } public static synchronized singleTonExample getInstance() { return ourInstance; } private singleTonExample() { } public void storeJson(JSONObject i1) { this.i1 = i1; } public String getJSON() { return i1.toString(); } }
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的一個專案活動檔案,然後單擊執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 –
現在點選上面的按鈕,它將使用全域性上下文在吐司中顯示 JSON 物件,如下所示 –
點選 這裡 下載專案程式碼
廣告