将上下文传递给Java类 - Android

时间:2018-02-05 20:11:48

标签: java android android-context

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

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String,int)'

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类的以下行:Preferences sharedPreferences = new Preferences(this);

我认为这与标准Java类在调用onCreate()方法之前没有上下文这一事实有关,但我对下一步的内容毫无头绪。我尝试过一些东西,但没有运气。

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

Using getResources() in non-activity class 您可以使用答案中提供的想法而不是继承活动。 通过上下文可能会导致内存泄漏并不是一个好主意。