Calling Fragment from RecyclerView Adapter - android-fragments

I have a recyclerView that shows a list in cardView. This recyclerview is located in one fragment that shown in a viewPager tab. I want to go to new Fragment when thumbnail in cardview is clicked.
I implemented following onBindViewHolder in order to have this functionality:
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment productDetailFragment = new ProductDetailFragment();
(FragmentActivity)mContext).getSupportFragmentManager().beginTransaction()
.replace(R.id.grid_page_recycler_view, productDetailFragment).commit();
}
});
But after running, it returns:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.support.v7.widget.RecyclerView.findMinMaxChildLayoutPositions(RecyclerView.java:3757)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3494)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3019)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:666)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15819)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15819)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
at android.view.View.measure(View.java:15819)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1965)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1146)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1356)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1046)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4603)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
What's the reason? It's notable that if I want to call another activity, it is easy to implement.
Thanks.
And I must say that there are several similar questions here, but I could not use them.

Create one method for replacing fragment in your MAinActivity.
Take ViewPager in a Fragment and push it from MainActivity.
Now Call replace fragment method in your recyclerView Adapter.
public void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.frame_container, fragment, backStateName);
ft.addToBackStack(backStateName);
ft.commit();
}
}

Related

Exception while registering to notification hub with userId in Xamarin Forms Android

I am working on a application in while i need to register the user to notification when he is logged in.When I call the registration while logging in I am getting an exception.Below is my code and exception.
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class PushNotificationServiceAndroid : FirebaseInstanceIdService, IPushNotificationService
{
const string TAG = "MyFirebaseIIDService";
NotificationHub hub;
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
NotificationHubConstants.Hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
}
public void RegisterToNotificationHub()
{
try
{
LoggingManager.Enter("RegisterToNotificationHub");
var tags = new List<string>() { };
if (Helpers.ApplicationContext.CurrentLoggedInUserId != 0)
{
tags.Add(Helpers.ApplicationContext.CurrentLoggedInUserId.ToString());
}
//NotificationHubConstants.Hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
LoggingManager.Exit("RegisterToNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
public void UnRegisterFromNotificationHub()
{
try
{
LoggingManager.Enter("UnRegisterFromNotificationHub");
hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
LoggingManager.Exit("UnRegisterFromNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
}
when the app opens OnTokenRefresh() is called.Once the user logged into the app i am calling RegisterToNotificationHub() through dependency service.But while registering into notification hub i.e, at
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
i am getting the following exception.
Java.Lang.RuntimeException: Exception of type 'Java.Lang.RuntimeException' was thrown.
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <7f42d9b804da4869b3155f4a330679c7>:0
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <2648c88210c943a888f6191db8d679d6>:0
at Android.Runtime.JNIEnv.CallObjectMethod (System.IntPtr jobject, System.IntPtr jmethod, Android.Runtime.JValue* parms) [0x0000e] in <871a122d80384347bfb5f33e1dee9682>:0
at WindowsAzure.Messaging.NotificationHub.Register (System.String pnsHandle, System.String[] tags) [0x00081] in <15e1a3139a484a5a85c0680e5d11bb86>:0
at BusinessViewChat.Droid.Dependencies.PushNotificationServiceAndroid.RegisterToNotificationHub () [0x00035] in E:\SourceTree\BusinessView\sourcecode\BusinessView\BusinessViewChat\BusinessViewChat.Android\Dependencies\PushNotificationServiceAndroid.cs:46
--- End of managed Java.Lang.RuntimeException stack trace ---
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:252)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:219)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:178)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:134)
at com.microsoft.windowsazure.messaging.NotificationHub.refreshRegistrationInformation(NotificationHub.java:296)
at com.microsoft.windowsazure.messaging.NotificationHub.registerInternal(NotificationHub.java:390)
at com.microsoft.windowsazure.messaging.NotificationHub.register(NotificationHub.java:143)
at mono.java.lang.RunnableImplementor.n_run(Native Method)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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)
Can any one please help me in solving the issue.Thanks in advance.
It must be added to your manifest file under the application tag.
The next:
<uses-library android: name = "org.apache.http.legacy" android: required = "false" />
For more information visit the official documentation
I hope I helped you, Regards
I got this error message because of a space in tags. After removing the space it worked.
Example:
I was using:
tags.Add("mill_id: 1313");
After changing for:
tags.Add("mill_id:1313");
It worked.
Check your tags to see if any character is causing the error.

New Activity from FloatingActionButton

i would launch an activity with a click in a floating action button, but when i click this, I get "Unfortunately, ... has stopped.". please help me!
questo è il codice del bottone di default, and this works
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
When change the code of a snackbar with the code of a new activity, this does not work
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity=new Intent (getApplicationContext(),add.class);
startActivity(launchactivity);
}
});
This is my logcat
09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fra31.tradebooks, PID: 6353
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: 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:2356)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
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 com.example.fra31.tradebooks.add.onCreate(add.java:47)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5289) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115) 
you should try this.
Intent launchactivity = new Intent(MainActivity.this, add.class);
startActivity(launchactivity);
Intent launchactivity=new Intent (MainActivity.this,add.class);
startActivity(launchactivity);
and you should go to androidmanifest.xml and define your activity as this :
<activity android:name=".MainActivity">
</activity>

GoogleApiClient.Builder.enableAutoManage in Fragment throws IllegalStateException: Recursive entry to executePendingTransactions

I have an AppCompatActivity that has 3 tabs using FragmentTabHost. One of the tabs uses LocationServices. I would like to have the smoothest possible user experience:
If the LocationService is off in the android system, and only if the user chooses the tab that needs the Location I would like to display the AlertDialog to let the user turn on the Location in the system settings.
I have a helper class that is supposed to do all this and it does work in 3 other places in my app. In those 3 places it works "directly" in the Activity, however in this place it needs to work "within" the Fragment of the tab.
The problem is that if I have the line:
builder.enableAutoManage(activity, 0, this);
then builder.build() throws an exception: IllegalStateException: Recursive entry to executePendingTransactions
Any idea how can I achieve my goal?
Here are some related code fragments:
public class CityPreferences extends AppCompatActivity {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("available_cities")
.setIndicator(getString(R.string.tab_all_cities))
, AvailableCityFragment.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("nearby_cities")
.setIndicator(getString(R.string.tab_nearby_cities))
, NearbyCityFragment.class, null);
}
}
In NearbyCityFragment I have this 1 line of code:
class NearbyCityFragment extends Fragment {
...
LocationServiceHelper.getInstance().startOrDisplayDialog(getActivity());
(I tried it in onAttach, onStart, onResume)
And here's my helper class' function:
public class LocationServiceHelper implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks {
public boolean startOrDisplayDialog(#NonNull final FragmentActivity activity) {
final boolean servicesConnected = GooglePlayServicesHelper.checkOrDisplayDialog(activity);
if (servicesConnected) {
final boolean isEnabled = isLocationEnabledInSystem(activity);
if (isEnabled) {
if (null == mGoogleApiClient) {
mContext = activity;
mActivity = activity;
final GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this);
// the next line seems to cause the problem:
builder.enableAutoManage(activity, 0, this);
mGoogleApiClient = builder
.build();
}
return start();
} else {
final Dialog dialog = getLocationDisabledDialog(activity);
GooglePlayServicesHelper.showDialog(dialog, activity);
}
}
return false;
}
And finally the exception:
06-10 10:23:04.831 26725-26725/com.fletech.android.redalert.debug E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.fletech.android.redalert.debug, PID: 26725
java.lang.IllegalStateException: Recursive entry to executePendingTransactions
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1473)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at com.google.android.gms.common.api.g.a(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.gI(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source)
at com.fletech.android.redalert.helper.LocationServiceHelper.startOrDisplayDialog(LocationServiceHelper.java:113)
at com.fletech.android.redalert.city.NearbyCityFragment.onAttach(NearbyCityFragment.java:44)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:907)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
I believe you must use a unique clientId each time you enable auto manager. From the documentation:
clientId - A non-negative identifier for this client. At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call stopAutoManage(FragmentActivity) on the previous client.

Webview crash after fragment tab change

I have a activity with 3 actionbar tabs. Each tab contains a webview which loads a URL at Fragment oncreate(). Everything is working fine but if i switch tabs quickly the onpagefinished appears after the tab change so when the calling fragment is gone, resulting in an NullPointerException. Is there a way to prevent this?
I tried in my fragment:
public void onDestroy() {
super.onDestroy();
try {
myWebView.stopLoading();
} catch (Exception e) {
}
try {
myWebView.clearView();
} catch (Exception e) {
}
and in my tab listener:
onTabSelected(Tab tab, FragmentTransaction ft) {
// StartActivity.mViewPager.setCurrentItem(tab.getPosition());
if (FinishedLoading == true){
ft.replace(R.id.fragment_container, fragment);
}
}
Both options don't prevent the APP to crash.
The error i recieve:
java.lang.NullPointerException
at com.***.Fragment1$MyWebViewClient.onPageFinished(Fragment1.java:233)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:389)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
I was facing this issue as well. If you haven't solved it, maybe you would like to try implementing onPause in your fragment like this:
#Override
public void onPause() {
if (webview.isShown() == false) {
webview.stopLoading();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
Where webview is your webview

Internet data connection fails

My users are reporting that when they download a JSON file using WiFi, the app works like charm, but when they attempt to download the same file using their data connection: GPRS, 3G, 3.5G etc... the app force closes. It doesn't happen with all types of smartphones, e.g, with my LG Optimus Black it doesn't happen.
To retrieve this file I use an AsyncTask.
private class GetData extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://url.com);
HttpResponse response = httpclient.execute(httpget);
strPlayers = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (IOException e) { e.printStackTrace(); }
finally { httpclient.getConnectionManager().shutdown(); }
return null;
}
protected void onPostExecute(Void result) {
Players players = new Gson().fromJson(strPlayers, Players.class);
quantity_darkmatter.setText(String.valueOf(players.userName));
}
}
Here's the StackTrace()
java.lang.RuntimeException: Unable to start activity ComponentInfo{carl.fri.fer.omegan/carl.fri.fer.omegan.Research}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at carl.fri.fer.omegan.Research.onStart(Research.java:613)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3791)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1632)
... 11 more
What can be the problem?
For non-WIFI the connection might take considerably more time, so it might be an issue of connection timeout, when that happens strPlayers will be blank and as there is no errorhandling in onPostExecute this might give Gson.fromJson hickups and make it throw an exception... try testing that strPlayers!=null before trying to parse it or putting it in a try-catch block to see if it throws an exception of some sort.
Is there any output of the e.printStackTrace() in the doInBackground function?

Resources