Android开发:FragmentCategory中SharedPref空指针无法获取ApiUrl
我是Android开发新手,在FragmentCategory中尝试从SharedPref获取ApiUrl时遇到空指针异常,报错信息如下:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.kannada.newspaper.india.utils.SharedPref.getApiUrl()' on a null object reference
多次尝试仍未解决,相关代码如下:
FragmentCategory 核心代码
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view,savedInstanceState); this.callbackCall = RestAdapter.createAPI(sharedPref.getApiUrl()).getHome(AppConfig.REST_API_KEY); this.callbackCall.enqueue(new Callback<CallbackHome>() { public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) { CallbackHome responseHome = response.body(); if (responseHome == null || !responseHome.status.equals("ok")) { return; } displayData(responseHome); } private void displayData(CallbackHome responseHome) { displayCategory(responseHome.category); } public void onFailure(Call<CallbackHome> call, Throwable th) { Log.e("onFailure", th.getMessage()); if (!call.isCanceled()) { } } }); }
SharedPref 类代码
public class SharedPref { private Context context; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch"; public SharedPref(Context context) { this.context = context; sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); } public Boolean getIsDarkTheme() { return sharedPreferences.getBoolean("theme", false); } public void setIsDarkTheme(Boolean isDarkTheme) { editor.putBoolean("theme", isDarkTheme); editor.apply(); } public void setFirstTimeLaunch(boolean isFirstTime) { editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime); editor.commit(); } public boolean isFirstTimeLaunch() { return sharedPreferences.getBoolean(IS_FIRST_TIME_LAUNCH, true); } public void setDefaultFilterRecipes(int i) { editor.putInt("filter", i); editor.apply(); } public Integer getCurrentFilterRecipes() { return sharedPreferences.getInt("filter", 0); } public void updateFilterRecipes(int position) { editor.putInt("filter", position); editor.apply(); } public Integer getRecipesViewType() { return sharedPreferences.getInt("recipes_list", RECIPES_GRID_2_COLUMN); } public void updateRecipesViewType(int position) { editor.putInt("recipes_list", position); editor.apply(); } public void setYoutubeApiKey() { editor.putInt("youtube_api_key", 0); editor.apply(); } public void saveConfig(String api_url, String application_id) { editor.putString("api_url", api_url); editor.putString("application_id", application_id); editor.apply(); } public String getApiUrl() { return sharedPreferences.getString("api_url", "https://kalviaruvi.com/demoandroid/your_recipes_app/"); } public String getApplicationId() { return sharedPreferences.getString("application_id", "com.app.yourrecipesapp"); } public void saveCredentials(String youtube_api_key, String fcm_notification_topic, String onesignal_app_id, String more_apps_url) { editor.putString("youtube_api_key", youtube_api_key); editor.putString("fcm_notification_topic", fcm_notification_topic); editor.putString("onesignal_app_id", onesignal_app_id); editor.putString("more_apps_url", more_apps_url); editor.apply(); } public String getYoutubeAPIKey() { return sharedPreferences.getString("youtube_api_key", "0"); } public String getFcmNotificationTopic() { return sharedPreferences.getString("fcm_notification_topic", "your_recipes_app_topic"); } public String getOneSignalAppId() { return sharedPreferences.getString("onesignal_app_id", "0"); } public String getMoreAppsUrl() { return sharedPreferences.getString("more_apps_url", "https://play.google.com/store/apps/developer?id=Solodroid"); } }
解决方案
核心原因
你在FragmentCategory中使用的sharedPref对象未初始化,处于空引用状态,调用其getApiUrl()方法时触发空指针异常。
修复步骤
在FragmentCategory中声明SharedPref成员变量:
private SharedPref sharedPref;在
onViewCreated方法开头初始化sharedPref(推荐用requireContext()确保Context非空):sharedPref = new SharedPref(requireContext());完整修改后的
onViewCreated方法:@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // 初始化SharedPref实例 sharedPref = new SharedPref(requireContext()); this.callbackCall = RestAdapter.createAPI(sharedPref.getApiUrl()).getHome(AppConfig.REST_API_KEY); this.callbackCall.enqueue(new Callback<CallbackHome>() { public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) { CallbackHome responseHome = response.body(); if (responseHome == null || !responseHome.status.equals("ok")) { return; } displayData(responseHome); } private void displayData(CallbackHome responseHome) { displayCategory(responseHome.category); } public void onFailure(Call<CallbackHome> call, Throwable th) { Log.e("onFailure", th.getMessage()); if (!call.isCanceled()) { // 可添加失败后的UI提示或重试逻辑 } } }); }
优化建议(可选)
如果多个页面需要使用SharedPref,建议将其改造为单例模式,避免重复初始化并减少内存泄漏风险:
public class SharedPref { private static SharedPref instance; private Context context; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch"; // 私有构造方法,避免外部直接实例化 private SharedPref(Context context) { this.context = context.getApplicationContext(); // 使用ApplicationContext避免内存泄漏 sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); } // 获取单例实例 public static synchronized SharedPref getInstance(Context context) { if (instance == null) { instance = new SharedPref(context); } return instance; } // 原有方法保持不变... }
在Fragment中使用单例:
sharedPref = SharedPref.getInstance(requireContext());
内容的提问来源于stack exchange,提问作者atozcodes
相关产品推荐
相关产品推荐

