gpt4 book ai didi

java - 调用 headlessfragment 时 Android Studio : Error of java. lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 03:05:16 25 4
gpt4 key购买 nike

我有一个主要 Activity 和一个 headless Fragment。
headless Fragment 应该获取要记录的手机的 IMEI 号码并返回到主 Activity。
我已经被这个错误困扰了几个小时,而且我似乎无法摆脱它。

这是日志猫:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidproject.example, PID: 5418
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidproject.example/com.androidproject.example.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.Activity.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.Activity.getApplicationContext()' on a null object reference
at com.androidproject.example.HeadlessFragment.loadIMEI(HeadlessFragment.java:110)
at com.androidproject.example.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Application terminated.

这是 MainActivity 中代码的相关部分:

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

mDeviceCode = (TextView)findViewById(R.id.device_code);

// Initializing headless fragment
mFragment =
(HeadlessFragment) getFragmentManager()
.findFragmentByTag("IMEILoader");

if(mFragment == null) {
mFragment = new HeadlessFragment();
getFragmentManager().beginTransaction()
.add(mFragment, "IMEILoader").commit();
}
if(mFragment != null){
mNumber = mFragment.loadIMEI(); //Here's the error
mDeviceCode.setText(Html.fromHtml("<b>IMEI</b>: " + mFragment.loadIMEI()));
}

这是 HeadlessFragment 代码:

    //Called when the 'loadIMEI' function is triggered.
public String loadIMEI() {

if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestPermissions();
} else {
// READ_PHONE_STATE permission is already been granted.
RecordedIMEI = permissionGrantedActions();
}
if(RecordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
return RecordedIMEI;
}

public String permissionGrantedActions() {


//Get IMEI Number of Phone
TelephonyManager tm =(TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);

String IMEINumber = tm.getDeviceId();

//RecordedIMEI = IMEINumber;

if(IMEINumber != null) {
Log.i("IMEI Loader", "IMEI number recorded!");
}
return IMEINumber;
}
}

我尝试了不同的方法,但没有成功。我认为 getActivity().getApplicationContext() 没有指向任何地方,这意味着在 headless fragment 附加到 mainactivity 之前调用它?
我已经被困在这个问题上很长一段时间了,需要一些帮助。

最佳答案

我认为你对“ headless fragment ”的想法是错误的,因为......

A Fragment represents a behavior or a portion of user interface in an Activity.

您似乎想要一个静态实用程序类来保存上下文并可以调用一些权限。从代码和其他答案中删除 extends Fragment ,这基本上就是您剩下的。

把它变成单例,你就不需要到处都需要Context参数了。

(代码未经测试)

可能无法完全工作。例如,不确定 ActivityCompat.OnRequestPermissionsResultCallback 的工作原理...

但它公开了您所需的功能,而无需解决 Fragment 生命周期。

public final class IMEILoader {
public static IMEILoader mInstance;
private Context mContext;

private IMEILoader() {}
private IMEILoader(Context c) {
this.mContext = c;
}

// Singleton pattern
public static IMEILoader getInstance(Context c) {
if (!(c instanceof ActivityCompat.OnRequestPermissionsResultCallback)) {
throw new Exception("Passed context not implementing permission callbacks");
}
if (mInstance == null) mInstance = new IMEILoader(c);
return mInstance;
}

public String load() {
String recordedIMEI = null;

if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestPermissions();
} else {
// READ_PHONE_STATE permission is already been granted.
recordedIMEI = permissionGrantedActions();
}
if(recordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
return recordedIMEI;
}

public String permissionGrantedActions() {
return null;
}


}

您可以在 Activity 中使用它,例如

class FooActivity extends AppCompatActivity impelements ActivityCompat.OnRequestPermissionsResultCallback {
private IMEILoader loader;
...

public void onCreate(Bundle b) {
...
loader = IMEILoader.getInstance(MainActivity.this);
String blah = loader.load();
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
...

}

关于java - 调用 headlessfragment 时 Android Studio : Error of java. lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com