Why does my Activity get destroyed upon adding a fragment (#2)? - java

I want to make it clear that this question will look very similar to one I asked earlier, but that I'm not asking exactly the same thing.
In my previous question, I got a RuntimeException/IllegalStateException, which told me my Activity got destroyed upon adding a new fragment.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
In that case, it turned out it had to do with me creating new instances of MainActivityin an invalid way:
MainActivity ma = new MainActivity();
(PSA: Don't do the above, use MainActivity ma = (MainActivity) getActivity(); instead.)
I have now corrected this in my entire project, and am getting almost exactly the same error. Let me be clear: I (think I) know the original error was fixed, because I got a different error in between these two RE's, which I was able to fix myself.
To reiterate on my gibberish: Got the first RE, fixed it with the answer on my question, got a different error, fixed that myself, got almost exactly the same RE.
I have searched through my entire project to see if I had anything similar to the error I made before, but I can't find anything, so here I am. So basically, the answer I got on my previous question fixed my issue, temporarily. That answer however, does not help me with this new error I'm getting, that's why I'm asking this question.
TL;DR: Answer on Q1 fixed my issue at first(which makes it a working answer), but it does not fix the issue I'm having right now, which is almost the same.
The actual question
So, now we've got that bit out of the way, let's get on with my issue. So, I'm getting a RuntimeException/IllegalStateExcetion:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}:
java.lang.IllegalStateException: Activity has been destroyed
(PS. It's only a RE because I have my app navigate to the GeneralSettings fragment on startup, for debugging ease.)
I've read up on this kind of error, but nothing I could find that applies on my project.
So, what is causing this RuntimeException/IllegalStateException?
Full log
04-05 14:17:53.140 23411-23411/? I/art: Not late-enabling -Xcheck:jni (already on)
04-05 14:17:53.190 23411-23411/com.example.tim.timapp W/System: ClassLoader referenced unknown path: /data/app/com.example.tim.timapp-1/lib/x86_64
04-05 14:17:53.210 23411-23411/com.example.tim.timapp D/TEST DBHandler: sInstance == null
04-05 14:17:53.370 23411-23411/com.example.tim.timapp D/AndroidRuntime: Shutting down VM
04-05 14:17:53.370 23411-23411/com.example.tim.timapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 23411
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
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.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:276)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:58)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.BackStackRecord.run(BackStackRecord.java:793)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
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) 
MainActivity (Snippet)
package com.example.tim.timapp;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static boolean isMainShown = false;
private static boolean isSettingsShown = false;
private static boolean doSavePopup = false;
private static String backTitle = "";
private String tag = "TEST MA";
DBHandler dbHandler;
Menu menu;
public void DrawVariableFragments(String base,String token){
// FragmentManager fm = getFragmentManager();
ArrayList<String> Data;
dbHandler = DBHandler.getInstance(this);
int AmountOfEntries;
int SettingsContainer;
String SettingsTag;
Fragment SettingsVariableFragment;
Fragment SettingsEmptyFragment;
if (base.equalsIgnoreCase("StuffManager")) {
Data = new ArrayList<String>() {{add("StuffManager"); add("name"); add("tag"); }};
SettingsContainer = R.id.FragmentContainer2;
SettingsTag = getString(R.string.navdrawer_stuffmanager);
SettingsVariableFragment = new StuffManagerVariableFragment();
SettingsEmptyFragment = new StuffManagerEmptyFragment();
} else if (base.equalsIgnoreCase("GeneralSettings")) {
Data = new ArrayList<String>() {{add("GeneralSettings"); add("name"); add("ip"); add("port"); add("username"); add("pass"); }};
SettingsContainer = R.id.FragmentContainerGeneralSettings;
SettingsTag = getString(R.string.navdrawer_generalsettings);
SettingsVariableFragment = new GeneralSettingsVariableFragment();
SettingsEmptyFragment = new GeneralSettingsEmptyFragment();
} else {
Log.e(tag, "String Base not recognised");
return;
}
AmountOfEntries = dbHandler.returnArray(base, Data.get(1)).size();
FragmentManager fm = getFragmentManager().findFragmentByTag(SettingsTag).getChildFragmentManager();
if ((dbHandler.returnArray(base, Data.get(1))).size() == 0 ) {
// Log.d(tag, "SettingsContainer1: " + String.valueOf(SettingsContainer) + "; SettingsEmtpyFragment1: " + SettingsEmptyFragment + "; Base1: " + base);
fm.beginTransaction().add(SettingsContainer, SettingsEmptyFragment, (base + "EmptyFragment")).commit();
fm.executePendingTransactions();
return;
}
if (AmountOfEntries > 0) {
String EmptyFragName = (base + "EmptyFragment");
if ((fm.findFragmentByTag(EmptyFragName)) != null) {
fm.beginTransaction().remove(fm.findFragmentByTag(EmptyFragName)).commit();
fm.executePendingTransactions();
}
for (int i = 0; i < AmountOfEntries; i++) {
ArrayList<String> fragmentData = new ArrayList<>();
for (int k=1; k < Data.size(); k++) {
int j=k-1;
fragmentData.set(j, (dbHandler.returnArray(base, Data.get(k)).get(j)));
}
if (token.equalsIgnoreCase("edit")) {
LinearLayout linearLayout = (LinearLayout) findViewById(SettingsContainer);
linearLayout.removeAllViews();
DrawVariableFragments(base ,"draw");
} else if (token.equalsIgnoreCase("add")) {
if (fm.findFragmentByTag(fragmentData.get(i)) == null) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
} else if (token.equalsIgnoreCase("draw")) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
}
} else {
Log.d("TEST", "WTF, nameArray.size != 0 && !> 0");
}
}
}
GeneralSettingsFragment (Snippet)
package com.example.fragments.Settings;
public class GeneralSettingsFragment extends Fragment {
MainActivity ma;
DBHandler dbHandler;
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
ma = (MainActivity) getActivity();
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
}

You are still doing things in an unsupported way. In MainActivity.DrawVariableFragments() you are creating a new GeneralSettingsVariableFragment() and then call getChildFragmentManager() on it and attempt to commit a fragment.
The GeneralSettingsFragment has not yet been attached to an Activity so it does not have a host. This throws the IllegalStateException("Activity has been destroyed") exception you are seeing when you try to commit the FragmentTransaction.
It is unclear why you are creating a new GeneralSettingsVariableFragmentwhen you are already inside a new instance of one.
To properly lookup an existing fragment use getFragmentManager().findFragmentByTag(...) or getFragmentManager().findFragmentById(...).

Related

google tells me that my app crashes on (only) Google Pixel 2 (virtuel)

I'm trying to publish my app in google play console.
But it tells me that it crashes on Google Pixel 2 (virtuel) (works on the 9 others) with 2 errors (very similar)
Google Pixel 2 (virtuel) 1080x1920 Android 12 (SDK 31) - x86_64 en_US
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
Detail:
FATAL EXCEPTION: Thread-2
Process: xxxxxxxx, PID: 8724
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
at xxxxxxxx.models.StockInputDialog.lambda$init$9$xxxxxxxx-models-StockInputDialog(StockInputDialog.java:417)
at xxxxxxxx.models.StockInputDialog$$ExternalSyntheticLambda9.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1)
at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:5)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1)
at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5)
at androidx.test.espresso.action.Tap.-$$Nest$smsendSingleTap(Unknown Source:0)
at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1)
at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:2)
at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:21)
at androidx.test.espresso.ViewInteraction.-$$Nest$mdoPerform(Unknown Source:0)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:6)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
My code is explained (and the reason why) startActivityForResult migration, call registerForActivityResult outside activity, and simplified to the maximum:
public class StockActivity extends AppCompatActivity implements DialogCloseListener {
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stockCameraActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
stockGalleryActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (id == R.id.action_add) {
mStockInputDialog = new StockInputDialog(this, stockCameraActivityResultLauncher, stockGalleryActivityResultLauncher,);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
public class StockInputDialog {
private final Context mContext;
private AlertDialog mInputDialog;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
public StockInputDialog(Context context, ActivityResultLauncher<Intent> pStockCameraActivityResultLaunchera, ActivityResultLauncher<Intent> pStockGalleryActivityResultLauncher) {
mContext = context;
stockCameraActivityResultLauncher = pStockCameraActivityResultLaunchera;
stockGalleryActivityResultLauncher = pStockGalleryActivityResultLauncher;
LayoutInflater li = LayoutInflater.from(this.mContext);
mPromptsView = li.inflate(R.layout.text_input_stock, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.mContext);
alertDialogBuilder.setView(mPromptsView);
final ImageButton imgButtonCam = mPromptsView.findViewById(R.id.addCam);
final ImageButton imgButtonGal = mPromptsView.findViewById(R.id.addGal);
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.foo.bar.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
stockCameraActivityResultLauncher.launch(intent); <= ERROR
});
imgButtonGal.setOnClickListener(view -> {
stockGalleryActivityResultLauncher.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)) <= ERROR
});
}
}
The 2 errors correspond to the 2 launch()
What I don't understand is that I'm using this same principle elsewhere in the application without an error being raised.
No more crashes when testing the "nullity" of the launchers (#Abdo21 2nd answer).
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.novazur.donteat.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
if (stockCameraActivityResultLauncher != null)
stockCameraActivityResultLauncher.launch(uri);
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
imgButtonGal.setOnClickListener(view -> {
if (stockGalleryActivityResultLauncher != null)
stockGalleryActivityResultLauncher.launch("image/*");
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
That's what I should have done from the start. I'm a little sorry for not having thought of it, it's so obvious. I guess it's related to the creation of the AlertDialog which should not allow immediate access to the launchers. What I don't understand in this case is why only the Pixel 2 crashes, but problem seems to be solved for the moment. Thanks all.

Android NULL Pointer Exception and Fragment data transmission [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}

Android: Fragment is not attached to Activity error

So I'm working on an app and I had this part working for days, and out of no where it just stopped working for no reason...
I also had the same error when I was trying to use another headless fragment in my MainActivity, but ended up replacing the fragment with inner methods inside of the MainActivity and everything went back to working properly.
However, I can't rewrite every bit of code I have just to avoid using fragments. The fragment code is below.
public class IMEIFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback{
public static final String TAG_IMEI = "IMEILoader";
protected Activity mActivity;
private String RecordedIMEI;
//public static final String CHECK_INTERNET = "network_connection";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return null; //Do we need this at all?
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = context instanceof Activity ? (Activity) context : null;
mActivity = activity;
}
//Is this needed?
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
activity = getActivity();
if (isAdded() && activity != null) {
super.onAttach(activity);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mActivity = activity;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
public String loadIMEI(Context context) {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestPermissions(context);
} else {
// READ_PHONE_STATE permission is already been granted.
RecordedIMEI = permissionGrantedActions(context);
}
if (RecordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
} else {
// READ_PHONE_STATE permission is already been granted.
RecordedIMEI = permissionGrantedActions(context);
}
if (RecordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
return RecordedIMEI;
}
private void requestPermissions(Context context) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
Log.i("loadIMEIService", "READ_PHONE_STATE permission not granted, asking for it...");
// TODO create proper notification content
PermissionHelper.requestPermissions(((PriceActivity) getActivity()),
new String[]{Manifest.permission.READ_PHONE_STATE},
Constants.PERM_REQUEST_PHONE_STATE,
getString(R.string.notify_perm_title),
getString(R.string.notify_perm_body),
R.drawable.ic_security);
}
}
// Callback received when a permissions request has been completed.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
boolean isGranted = false;
for (int i = 0; i < grantResults.length; i++)
if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE) && (grantResults[i] == PackageManager.PERMISSION_GRANTED))
isGranted = true;
if (isGranted) {
Context context = getActivity().getApplicationContext();
permissionGrantedActions(context);
}
else
Log.w("loadIMEIService", "READ_PHONE_STATE permission not granted. loadIMEI will not be available.");
}
public String permissionGrantedActions(Context context) {
//Have an object of TelephonyManager
TelephonyManager tm =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//Get IMEI Number of Phone
String IMEINumber = tm.getDeviceId();
if(IMEINumber != null) {
Log.i("loadIMEIService", "IMEI number recorded!");
}
return IMEINumber;
}
}
Error is below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.project1, PID: 5498
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.project1/com.android.project1.main.MainActivity}: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
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.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:805)
at android.app.Fragment.getString(Fragment.java:827)
at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)
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) 
And here's the relevant part of my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceCode = (TextView) findViewById(R.id.device_code);
// Initializing headless fragment
mFragment =
(IMEIFragment) getFragmentManager()
.findFragmentByTag("IMEILoader");
if (mFragment == null) {
mFragment = new IMEIFragment();
getFragmentManager().beginTransaction()
.add(mFragment, "IMEILoader").commit();
}
if (mFragment != null) {
mNumber = mFragment.loadIMEI(MainActivity.this);
mDeviceCode.setText(Html.fromHtml("<b>IMEI</b>: " + mNumber));
}
I literally had the exact same code working for over a week. Anyone knows what could be the problem?
Edit 1: The error is pointing to requestPermissions inside my fragment
Fragments should be self contained as much as possible. You are calling directly into your IMEIFragment from the activity,
Caused by: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:805)
at android.app.Fragment.getString(Fragment.java:827)
at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)
You can't do that. Adding the fragment via a transaction from the activity is an asynchronous operation. E.g., when the commit() method completes, the fragment is not initialized. Moreover, you have no way of knowing when it's initialized. That's why it should be self contained. The fragment decides when to call loadIMEI(), not the activity.
If you really need it to be initiated by the activity, you can add a callback from the fragment to the activity like,
void onFragmentReady(Fragment f);
Or something.
And yes, onCreateView() should return something. If your fragment really doesn't have any UI at all, you don't need it to be a fragment.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

The problem is as follows. I have a login activity (in Android Studio) which worked fine a few days before. I don't remember changing anything but when I run this one the previous time the app closed right after I clicked the login button. The last thing indicated was the toast about pre-execution of AsyncTask.
And I can't understand why there could be a NullPointerException.
I have almost the same code for my signup activity and it works fine.
Here is the log:
05-28 16:04:52.395 1218-1232/system_process V/WindowManager﹕ addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407 19927-19927/utanashati.reminder D/AndroidRuntime﹕ Shutting down VM
05-28 16:04:52.408 19927-19927/utanashati.reminder E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: utanashati.reminder, PID: 19927
java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-28 16:04:52.410 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 2 utanashati.reminder/.LoginActivity
EDIT 1
I had my eyes opened, the problem is not with LoginActivity, but with HomepageActivity. Here is the code:
import ...
public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected EditText mAddTaskText;
protected Spinner mPrioritySpinner;
protected Button mAddTaskButton;
protected int intPriority = 0;
protected String taskText;
protected Timestamp taskTimestamp;
protected Task userTask;
protected JsonGenerator taskJSON;
#Override
protected void onCreate(Bundle savedInstanceState) { // Starts activity. The state can be restored from savedInstanceState
super.onCreate(savedInstanceState); // Calls the superclass method (IMPORTANT)
setContentView(R.layout.activity_homepage); // Sets layout from activity_homepage.xml
mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner); // Creates an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.priorityList, android.R.layout.simple_spinner_item); // Specifies the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Applies the adapter to the spinner
mPrioritySpinner.setAdapter(adapter);
mPrioritySpinner.setOnItemSelectedListener(this);
mAddTaskText = (EditText) findViewById(R.id.addTaskEditText); // Finds View by its id in .xml file
mAddTaskButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();
Calendar taskCalendar = Calendar.getInstance(); // Creates new calendar
long taskTime = taskCalendar.getTimeInMillis(); // Gets time in milliseconds
taskTimestamp = new Timestamp(taskTime); // Creates new Timestamp
taskText = mAddTaskText.getText().toString(); // Gets description of the task
userTask.setDate(taskTimestamp); // Sets date
userTask.setText(taskText); // Sets text
/* Creating JsonGenerator */
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(taskJSON, userTask);
}
catch (IOException e) {
Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
}
/* Getting out email and password */
String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();
/* HTTP stuff */
HttpPoster get = new HttpPoster();
get.execute(userEmail, userPassword, taskJSON.toString());
}
});
}
public int getData (String username, String password, String taskJSON) {
try {
HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
String dataToEncode = username + ":" + password;
String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", encodedData);
try {
StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
httpPost.setEntity(taskEntity);
}
catch (UnsupportedEncodingException e) {
Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
}
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
return 1;
}
else if (statusCode == 404) { return 2; }
else if (statusCode == 500) { return 3; }
else if (statusCode == 409) { return 4; }
else { return statusCode; }
}
catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String priority = parent.getItemAtPosition(pos).toString(); // Gets chosen priority
Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
}
if (priority.equals("Low")) {
intPriority = 0;
}
else if (priority.equals("Medium")) {
intPriority = 1;
}
else if (priority.equals("High")) {
intPriority = 2;
}
userTask.setPriority(intPriority); // Sets chosen priority
}
public void onNothingSelected(AdapterView<?> parent) {
userTask.setPriority(intPriority); // Sets default priority ("0")
}
public class HttpPoster extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(String... params) {
return getData(params[0], params[1], params[3]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 1) {
Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
startActivity(takeUserHome);
}
else if (result == 2) {
Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
}
else if (result == 3) {
Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
}
else if (result == 4) {
Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
And XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="utanashati.testapp.HomepageActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Add a new task..."
android:id="#+id/addTaskEditText"
android:nestedScrollingEnabled="false"
android:minLines="1"
android:maxLines="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/prioritySpinner"
android:layout_alignRight="#+id/addTaskButton"
android:layout_alignEnd="#+id/addTaskButton"
android:layout_below="#+id/addTaskEditText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add task"
android:id="#+id/addTaskButton"
android:layout_below="#+id/prioritySpinner"
android:layout_centerHorizontal="true" />
</RelativeLayout>
It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout)
Check it.
mAddTaskButton is null because you never initialize it with:
mAddTaskButton = (Button) findViewById(R.id.addTaskButton);
before you call mAddTaskButton.setOnClickListener().
Check out this solution. It worked for me.....
Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app.
If yes, then change the id of them and then the app runs perfectly.
I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!!
Hope it works
That true,Mustafa....its working..its point to two layout
setContentView(R.layout.your_layout)
v23(your_layout).
You should take Button both activity layout...
solve this problem successfully
Check whether you have matching IDs in both Java and XML
Just define the button as lateinit var at top of your class:
lateinit var buttonOk: Button
When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:
buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)
After this you can use setonclicklistener for the button and you won't have any error.
You can see correct answer of this question: Android Kotlin findViewById must not be null
Make sure that while using :
Button "varName" =findViewById("btID");
you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.
Got the same error,
CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID);
If you have put the id correct or not.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Placing setOnClickListener in onStart method solved the problem for me.
Checkout "Android Lifecycle concept" for further clarification
mAddTaskButton.setOnClickListener(new View.OnClickListener()
you have a click listner but you haven't initialized the mAddTaskButton with your layout binding
Please check whether you have two Layout folder (e.g Layout & Layout-V21). The XML file should be same in both folders. That was the case for me.

NullPointerException on onPostExecute method

I’m having a navigation drawer for my app that contains a menu with which I can navigate between the fragments. The first fragment that i get after the app lunch is the Home which contains a listView and a footer attached in the bottom (is just for the test). The problem is when I lunch the Home fragment for the first time nothing happen and its work very well, but when I change the fragments from the navigation drawer and trying to get back the home fragment the app crash. The error log show me a null pointer Exception. Thes is my code detail
onCreateView method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.fragment_homes, container, false);
listView = (ListView) v.findViewById(R.id.homeList);
l = new HomeListAdapter(this, homeList);
if(l == null)
Log.i("tag","null");
listView.setAdapter(l);
} catch (InflateException e) {
}
return v;
}
onPostExecute method
#Override
protected void onPostExecute(final String res) {
/*try {
jObj = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
/* JSONArray j = null;
try {
j = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
// Parsing json
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition");
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
l.notifyDataSetChanged();
//pDialog.hide();
}
The error log
10-10 09:31:30.884 2447-2447/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2447
java.lang.NullPointerException
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:375)
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:277)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And this is exactly the line that cause the error : l.notifyDataSetChanged();. I notice that the error is just in the case when i'm trying to display the fragment for the secode time.
So any help please ? Thanks !
You need to use this in doInBackground.
#Override
protected Void doInBackground(void... ) {
try {
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition"); //give some other name in getter setter for setText in Home.java. It makes not to understand whether you are using setText for textview assigning.
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
postExecute is used to display UI. don't perform heavy operation like parsing in PostExecute.

Categories