Home » Android » java – Android exception running Android Studio Preferences activity template-Exceptionshub

java – Android exception running Android Studio Preferences activity template-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I’m having a “java.lang.IllegalStateException: Target fragment must implement TargetFragment interface” when running the Android Studio boilerplate available in the File->New->Activity->Settings Activity sample; The exception occurs when I reorient the device from portrait to landscape view and back again to the portrait view while having any of the preference dialogs inflated on top of the PreferenceScreen (code below); I tried to implement the TargetFragmentt interface, but I do not know what code to put in it. Pls refer to what I’m missing or doing wrong.

Thanks for the help!

Error log:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.preferences, PID: 1472
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.preferences/br.com.preferences.SettingsActivity}: java.lang.IllegalStateException: Target fragment must implement TargetFragment interface
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2370)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3892)
    at android.app.ActivityThread.access$900(ActivityThread.java:155)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1249)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5426)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: Target fragment must implement TargetFragment interface
    at androidx.preference.PreferenceDialogFragmentCompat.onCreate(PreferenceDialogFragmentCompat.java:81)
    at androidx.preference.ListPreferenceDialogFragmentCompat.onCreate(ListPreferenceDialogFragmentCompat.java:48)
    at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
    at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
    at androidx.fragment.app.FragmentManagerImpl.dispatchCreate(FragmentManagerImpl.java:2607)
    at androidx.fragment.app.FragmentController.dispatchCreate(FragmentController.java:235)
    at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:316)
    at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:106)
    at br.com.preferences.SettingsActivity.onCreate(SettingsActivity.java:17)
    at android.app.Activity.performCreate(Activity.java:5296)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2370) 
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3892) 
    at android.app.ActivityThread.access$900(ActivityThread.java:155) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1249) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:136) 
    at android.app.ActivityThread.main(ActivityThread.java:5426) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:515) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
    at dalvik.system.NativeStart.main(Native Method) 

SettingsActivity.java:

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.DialogPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

public class SettingsActivity extends AppCompatActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.settings_activity);
  getSupportFragmentManager()
   .beginTransaction()
   .replace(R.id.settings, new SettingsFragment())
   .commit();
  ActionBar actionBar = getSupportActionBar();
  if (actionBar != null) {
   actionBar.setDisplayHomeAsUpEnabled(true);
  }
 }

 public static class SettingsFragment extends PreferenceFragmentCompat
 implements DialogPreference.TargetFragment {
  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
   setPreferencesFromResource(R.xml.root_preferences, rootKey);
  }

  @Nullable
  @Override
  public < T extends Preference > T findPreference(@NonNull CharSequence key) {
   return super.findPreference(key);
  }
 }
}

res/xml/root_preferences.xml (the one supplied with the Android Studio File->New->Activity->Settings Activity):

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
   <PreferenceCategory app:title="@string/messages_header">
      <EditTextPreference
         app:key="signature"
         app:title="@string/signature_title"
         app:useSimpleSummaryProvider="true" />
      <ListPreference
         app:defaultValue="reply"
         app:entries="@array/reply_entries"
         app:entryValues="@array/reply_values"
         app:key="reply"
         app:title="@string/reply_title"
         app:useSimpleSummaryProvider="true" />
   </PreferenceCategory>
   <PreferenceCategory app:title="@string/sync_header">
      <SwitchPreferenceCompat
         app:key="sync"
         app:title="@string/sync_title" />
      <SwitchPreferenceCompat
         app:dependency="sync"
         app:key="attachment"
         app:summaryOff="@string/attachment_summary_off"
         app:summaryOn="@string/attachment_summary_on"
         app:title="@string/attachment_title" />
   </PreferenceCategory>
</PreferenceScreen>

The build.gradle:

   apply plugin: 'com.android.application'
   android {
        compileSdkVersion 29
        buildToolsVersion "29.0.1"
        defaultConfig {
            applicationId "br.com.preferences"
            minSdkVersion 15
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'androidx.preference:preference:1.1.0'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    }
How to&Answers:

The Android Studio boilerplate happens to be wrong.
Just check if there was a previous saved instance before creating a new one:

if(savedInstanceState == null) {  
   getSupportFragmentManager().beginTransaction().replace(R.id.settings, new SettingsFragment()).commit();
}

Maybe it might be of help to other newbies.