在上下文中传递给 Java Class - Android

Passing in context to a Java Class - Android

当我在我的应用程序 (Template1Activity) 中打开此 activity 时,应用程序崩溃并显示以下消息:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

我的 Template1Activity 代码是:

package com.idleappsinc.smartmirror;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Luke on 04/02/2018.
 */

public class Template1Activity extends AppCompatActivity {

    Preferences sharedPreferences;
    TimeModule timeModule = new TimeModule();

    TextView timeDisplayTextView;
    TextView timeLocationTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_template_1);
        sharedPreferences = new Preferences(this);

        timeDisplayTextView = findViewById(R.id.time_display_text_view);
        timeLocationTextView = findViewById(R.id.time_location_text_view);

        timeModule.startTimer(timeDisplayTextView);
        timeLocationTextView.setText(timeModule.getCurrentLocation());


        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

    }

}

我的 TimeModule 代码是:

package com.idleappsinc.smartmirror;


import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.widget.TextView;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Created by Luke on 05/02/2018.
 */

public class TimeModule extends Activity {

    Preferences sharedPreferences = new Preferences(this);
    List<Address> addressList;

    @SuppressWarnings({"MissingPermission"})
    public String getCurrentLocation() {
        String currentLocation = "";

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            String area = addressList.get(0).getLocality();
            String country = addressList.get(0).getCountryCode();

            currentLocation = area + ", " + country;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return currentLocation;
    }

    public void startTimer(final TextView timeDisplayTextView) {

        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {

                    if (sharedPreferences.getBooleanValue(getResources().getString(R.string.preference_time_clock_hours))) {
                        // User wants 24 hour format

                        if (sharedPreferences.getBooleanValue(getResources().getString(R.string.preference_time_segment_seconds))) {
                            // User wants to see seconds
                            int secondsLength = String.valueOf(Calendar.getInstance().get(Calendar.SECOND)).length();
                            int minutesLength = String.valueOf(Calendar.getInstance().get(Calendar.MINUTE)).length();

                            if (secondsLength == 1) {
                                if (minutesLength == 1) {
                                    // Seconds = 0-9
                                    // Minutes = 0-9
                                    timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND));
                                } else {
                                    // Seconds = 0-9
                                    timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND));
                                }
                            } else {
                                if (minutesLength == 1) {
                                    // Minutes = 0-9
                                    timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND));
                                } else {
                                    // Seconds = 0-9
                                    timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND));
                                }
                                timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND));
                            }

                        } else {
                            timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
                        }


                    } else {
                        // The user wants the 12 hours format

                        if (sharedPreferences.getBooleanValue(getResources().getString(R.string.preference_time_segment_seconds))) {
                            int secondsLength = String.valueOf(Calendar.getInstance().get(Calendar.SECOND)).length();
                            int minutesLength = String.valueOf(Calendar.getInstance().get(Calendar.MINUTE)).length();

                            if (secondsLength == 1) {
                                Calendar cal = Calendar.getInstance();
                                if (cal.get(Calendar.AM_PM) == Calendar.PM) {
                                    if (minutesLength == 1) {
                                        // Seconds = 0-9
                                        // Minutes = 0-9
                                        // PM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND) + "pm");
                                    } else {
                                        // Seconds = 0-9
                                        // PM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND) + "pm");
                                    }
                                } else {
                                    if (minutesLength == 1) {
                                        // Seconds = 0-9
                                        // Minutes = 0-9
                                        // AM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND) + "am");
                                    } else {
                                        // Seconds = 0-9
                                        // Minutes = 0-9
                                        // AM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":0" + Calendar.getInstance().get(Calendar.SECOND) + "am");
                                    }
                                }

                            } else {
                                Calendar cal = Calendar.getInstance();
                                if (cal.get(Calendar.AM_PM) == Calendar.PM) {
                                    if (minutesLength == 1) {
                                        // Minutes = 0-9
                                        // PM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND) + "pm");
                                    } else {
                                        // PM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND) + "pm");
                                    }
                                } else {
                                    if (minutesLength == 1) {
                                        // Minutes = 0-9
                                        // AM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":0" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND) + "am");
                                    } else {
                                        // AM
                                        timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND) + "am");
                                    }
                                }
                            }
                        } else {
                            Calendar cal = Calendar.getInstance();
                            if (cal.get(Calendar.AM_PM) == Calendar.PM) {
                                timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + "pm");
                            } else {
                                timeDisplayTextView.setText(Calendar.getInstance().get(Calendar.HOUR) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + "am");
                            }
                        }

                    }

                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    //also call the same runnable to call it at regular interval
                    if (sharedPreferences.getBooleanValue(getResources().getString(R.string.preference_time_segment_seconds))) {
                        handler.postDelayed(this, 1000);
                    } else {
                        handler.postDelayed(this, (60 - Calendar.getInstance().get(Calendar.SECOND)) * 1000);
                    }

                }
            }
        };
        handler.postDelayed(runnable, (1 - Calendar.getInstance().get(Calendar.MILLISECOND)) * 1000);

    }


}

TimeModule class 中的以下行发生错误:Preferences sharedPreferences = new Preferences(this);

我认为这与标准 Java class 在调用 onCreate() 方法之前没有上下文这一事实有关,但我对此一无所知接下来会发生什么。我尝试了一些东西,但没有运气。

Java Class TimeModule 只是一个 Java Class,而不是链接到布局的 Class。它扩展 Activity 的 erason 是这样我可以访问某些方法,例如 getResources()

因为您在 Template1Activity 中自己创建了 TimeModule 对象。使用构造函数将 Template1Activity 的上下文传递给它。然后你可以在构造函数中初始化sharedPreference

TimeModule(Context context){
    sharedPreferences = new Preferences(this);
}

在非 activity class 中使用 getResources() 你可以使用答案中给出的想法而不是继承 activity。
传递上下文不是个好主意,它可能会导致内存泄漏。