Start BottomSheetFragment for result - java

I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside
#Override
public void onDismiss(DialogInterface dialog) {
getActivity().setResult(Activity.RESULT_OK, null);
super.onDismiss(dialog);
}
but activity's method onActivityResult not called. What am I doing wrong?
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
super.onActivityResult(requestCode, resultCode, data);
}
Dialog start method
BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
Bundle bundle = new Bundle();
bottomSheetFragment.setArguments(bundle);
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

onActivityResult() is used for getting a result from another Activity.
More on this: https://developer.android.com/training/basics/intents/result
If you want to send some data from Fragment to Activity, you can do it either by defining an interface or call a method in the Activity by casting it to the specific Activity.
class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
YourBottomSheetDialogFragment bottomSheetFragment = new YourBottomSheetDialogFragment();
Bundle bundle = new Bundle();
bottomSheetFragment.setArguments(bundle);
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
}
public void setResultFromFragment(String data) {
...
}
}
/**
* Calling Activity's method from Fragment
*/
class YourBottomSheetDialogFragment extends BottomSheetDialogFragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity) getActivity()).setResultFromFragment("");
}
}

I decided to implement the interface as suggested to me by DEVV911
interface OnFinishedListener {
void onFinished(ArrayList<TestCard> acceptList, ArrayList<TestCard> rejectList);
void onFailure(Throwable t);
}
add it into dialog's construction method
private TestActivityContract.OnFinishedListener onFinishedListener;
BottomSheetFragment(TestActivityContract.OnFinishedListener onFinishedListener) {
this.onFinishedListener = onFinishedListener;
}
And call the onFinished method in onDismiss
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
onFinishedListener.onFinished(acceptList, rejectList);
}

Related

how to make OnNewIntent work inside tabs

I am working on a project where I have 3 tabs. The first tab is used to write information to NFC tag where the other 2 tabs are used to read the information from the NFC tag. However, I am facing a problem with OnNewIntent() method. As I understood correctly from reading online is that this method is used only in activities and not in fragments. I have looked at similar questions and answers but I don't fully understand what needs to be done to avoid this issue in my situation.
Here is my code for the first tab where I write some data to NFC tag:
public class Home extends Fragment {
NfcAdapter nfcAdapter;
Button writebtn;
Tag tag;
EditText txtName, txtCountry, txtID;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
nfcAdapter = NfcAdapter.getDefaultAdapter(getContext());
txtName = (EditText)view.findViewById(R.id.personName);
txtCountry= (EditText)view.findViewById(R.id.personCountry);
txtID= (EditText)view.findViewById(R.id.personID);
writebtn=(Button)view.findViewById(R.id.nfcWriteBtn);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.home, container,false);
return v;
}
#Override
public void onResume() {
super.onResume();
if(nfcAdapter !=null){
enableForegroundDispatchSystem();
}
}
#Override
public void onPause() {
super.onPause();
disableForegroundDispatchSystem();
}
protected void onNewIntent(final Intent intent) {
// super.onNewIntent(intent);
getActivity().getIntent();
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
Toast.makeText(getContext(), "NFC tag discovered!", Toast.LENGTH_SHORT).show();
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NdefMessage ndefMessage = createNdefMessage(txtName.getText().toString(), txtCountry.getText().toString(),txtID.getText().toString());
writeNdefMessage(tag, ndefMessage);
}
});
}
}
onNewIntent(Intent intent) belongs to Activity you cannot have it in fragment. What you can do is pass the data to your fragment whenever onNewIntent(Intent intent) get called in Activity. To achieve this You need to override onNewIntent() in Activity and notify the fragments about intent . Do not use getIntent() use the intent which is in argument.
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Notify fragment about the new intent
}
And your Fragments method should look like .
protected void onNewIntent( Intent intent) {
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
Toast.makeText(getContext(), "NFC tag discovered!", Toast.LENGTH_SHORT).show();
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NdefMessage ndefMessage = createNdefMessage(txtName.getText().toString(), txtCountry.getText().toString(),txtID.getText().toString());
writeNdefMessage(tag, ndefMessage);
}
});
}

cannot execute android activity

I'm trying to build an App for Android Lollipop (5.0). There is a login fragment and when i press login button then app automatically crashes. I'm sharing my code and error message please guide me.
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity {
protected CoreApplication coreApplication;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
coreApplication = (CoreApplication) getApplication();
}
}
BaseAuthenticatedActivity.java
public abstract class BaseAuthenticatedActivity extends BaseActivity {
#Override
protected final void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (!coreApplication.getAuth().getUser().isLoggedIn()) {
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
onCoreApplicationCreate(savedState);
}
protected abstract void onCoreApplicationCreate(Bundle savedState);
}
LoginActivity.java
public class LoginActivity extends BaseActivity implements View.OnClickListener, LoginFragment.CallBacks {
private static final int REQUEST_NARROW_LOGIN = 1;
private View loginButton;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.activity_login);
loginButton = findViewById(R.id.LoginJustChat);
if (loginButton != null) {
loginButton.setOnClickListener(this);
}
}
#Override
public void onClick(View view) {
if (view == loginButton)
startActivityForResult(new Intent(this, LoginNarrowActivity.class), REQUEST_NARROW_LOGIN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
if (requestCode == REQUEST_NARROW_LOGIN) {
finishLogin();
}
}
private void finishLogin() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
#Override
public void onLoggedIn() {
finishLogin();
}
}
LoginNarrowActivity.java
public class LoginNarrowActivity extends BaseActivity implements LoginFragment.CallBacks {
#Override
protected void onCreate(Bundle savedState){
super.onCreate(savedState);
setContentView(R.layout.activity_login_narrow);
}
#Override
public void onLoggedIn() {
setResult(RESULT_OK);
finish();
}
}
MainActivity.java
public class MainActivity extends BaseAuthenticatedActivity {
#Override
protected void onCoreApplicationCreate(Bundle savedState) {
}
}
BaseFragment.java
public abstract class BaseFragment extends Fragment {
protected CoreApplication application;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
application = (CoreApplication) getActivity().getApplication();
}
}
LoginFragment.java
public class LoginFragment extends BaseFragment implements View.OnClickListener {
private Button loginButton;
private CallBacks callBacks;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedState) {
View view = inflater.inflate(R.layout.fragment_login, root, false);
loginButton = (Button) view.findViewById(R.id.fragment_login_loginButton);
loginButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
if (view == loginButton) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
}
// because onAttach(Activity activity) is deprecated
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallBacks) {
callBacks = (CallBacks) context;
} else {
throw new ClassCastException(context.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
callBacks = null;
}
public interface CallBacks {
void onLoggedIn();
}
}
Error:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.example.usama.demoapp.fragments.LoginFragment$CallBacks.onLoggedIn()'
on a null object reference
Please guide me with this.
Welcome to Android !
You got a NullPointerException. It's a very common [and lovely; since it's rather easy to debug] exception in Java. Check your LoginFragment. The following method will cause this exception to raise.
#Override
public void onClick(View view) {
if (view == loginButton) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
}
A couple of notes in order to diagnose this error:
When you declare a class member with initializing it, in this casecallBacks, Java automatically initialize it to null.
Invoking any method on a null reference will result in NPE.
Okay, let's narrow down to your specific case. You declared a class member called callBacks but never initialized it, as well as, I can see no methods that assign something to it. Therefore, that class member always remains null and thereby any subsequent method invocation on it leads us to NPE.
As a solution, you should add a setter method to your LoginFragment class in which you set that callBacks. In other side supply this object where you first create an instance of this fragment.
Update #1
when i pass Activity instead of Context as parameter in onAttach method it works. but i want to know why it is causing the error?
The why is simple. Since your activity already implemented that interface, so passing it to your LoginFragment as context will result in the condition if (context instanceof CallBacks) becoming true. However, passing bare context won't result in establishment of that if statement.
can u please tell me how i can define setter?
It's pretty simple! Just as other regular method, declare a method like this:
public void setOnLoginListener(Callbacks listener){
this.callbacks = listener;
}
Update #2
where i need to define setOnLoginListener method
Inside the LoginFragment class.
and where should i call it
In your main activity where you first instantiate LoginFragment class.
with what parameters?
Your activity, which implements that Java interface.
You can avoid setting onClickListener for the button by having adding android:onClink="login" in your xml file and a function that looks like this in your java file:
public void login(View view) {
application.getAuth().getUser().setIsLoggedIn(true);
callBacks.onLoggedIn();
}
You can try writing a public setter for the callBacks object in LoginFragment and setting it from the activity instead, like this, supposing you defined your fragment in the activity's layout file:
public class LoginNarrowActivity extends BaseActivity implements LoginFragment.CallBacks {
#Override
protected void onCreate(Bundle savedState){
super.onCreate(savedState);
setContentView(R.layout.activity_login_narrow);
LoginFragment loginFragment = (LoginFragment)getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);
loginFragment.setCallBacks(this);
}
Actually the error was here in onAttach(Context context) when i pass Activity like this onAttach(Activity activity) then it worked. But i want to know why it is causing the error? and onAttach(Activity activity) is deprecated in android 5.0

Get onActivityResult when returning from startActivityForResult in Adapter

I am trying to return some data when a user clicks back from the Activity.
I am calling startActivityForResult from the adapter, but when I actually press back from the Activity, onActivityResult never seems to be called
Code is trimmed down for example
Fragment1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View mainView = inflater.inflate(R.layout.grid_view, container, false);
return mainView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.w(TAG, "in activity result");
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
}
Adapter
public Adapter(Context context, List<Item> objects) {
super(context, -1, objects);
this.context = context;
addAll(objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.grid_view_item, parent, false);
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
((Activity) context).((Activity) context).startActivityForResult(intent, 1);(intent, 1);
}
});
return view;
Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_view);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
denyEditPermission = extras.getBoolean("denyEditPermission");
}
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("denyEditPermission", denyEditPermission);
setResult(RESULT_OK, intent);
finish();
}
Since you use activity context to start the activity, you will get onActivityResult callback in activity, not in fragment. To get callback in fragment, you need to use fragment context/start activity in fagment itself. I would suggest interface approach to fix the issue here.Create an interface and implement it in your fragment and when the recommendationLayout is clicked, call the interface method from adapter so that you can handle the click event in fragment itself.
Something like,
Create an interface file -
public interface RecommendationClickListener {
public void onRecommendationClicked();
}
Fragment:
public class MyFragment extends Fragment implements RecommendationClickListener{
...
...
...
#Override
public void onRecommendationClicked() {
Intent intent = new Intent(getActivity(), NextActivity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mAdapter.setRecommendationClickListener(this);
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
Adapter:
private RecommendationClickListener mRecommendationClickListener;
public void setRecommendationClickListener(RecommendationClickListener recommendationClickListener) {
this.mRecommendationClickListener = recommendationClickListener;
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecommendationClickListener != null) {
mRecommendationClickListener.onRecommendationClicked();
}
}
});
The Broadcast solution is as follows:
In Fragment
Declare on top of the class
public final static String START_ACT = "com.yourcompanyname.appname.START_ACT";
private Radio radio;
On the createView initiate and register the receiver
//Initiate our receiver
radio = new Radio();
//Activate our recevier
getActivity().getApplicationContext().registerReceiver(radio, new IntentFilter(START_ACT));
Also in the fragment, create the receiver class and the mothod which calls the Activity
/**
* Receiver Class
* This setup checks for the incoming intent action to be able to
* attach more messages to one receiver.
*/
private class Radio extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(START_ACT)){
getDataFromActivity();
}
}
}
public void getDataFromActivity(){
Intent intent = new Intent(getActivity(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
After from anywhere in the application send message to our radio
context.sendBroadcast(new Intent(Fragment1.START_ACT));

How to login Facebook using nested fragment in Android

I have nested fragment like the following.
MainActivity
FragmentA
FragmentA1
FragmentA3
FragmentA2
FragmentB
FragmentB1
I want to login facebook from FragmentA3. But can not.
In FragmentA3, my app stop in onResume after called onActivityResult.
What should I do?
FragmentA3
public class FragmentA3 extends Fragment {
public static final String TAG = FragmentA3.class.getCanonicalName();
private UiLifecycleHelper mFbSdkUiHelper;
private OnLoggedListener mCallback;
private final List<String> permissions;
public OthersFBLogin() {
// Required empty public constructor
permissions = Arrays.asList("basic_info", "email");
}
public interface OnLoggedListener {
//Callback to notify about login success.
public void onLoginSuccess();
}
private final Session.StatusCallback mSessionCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.d(TAG,"onSessionStateChange");
if (state.isOpened()) {
mCallback.onLoginSuccess();
} else if (state.isClosed()) {
if (session != null) {
session.closeAndClearTokenInformation();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate");
super.onCreate(savedInstanceState);
mFbSdkUiHelper = new UiLifecycleHelper(getActivity(), mSessionCallback);
mFbSdkUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG,"onCreateView");
View rootView = inflater.inflate(R.layout.others_fblogin, container, false);
LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
loginButton.setFragment(this);
loginButton.setReadPermissions(permissions);
return rootView;
}
#Override
public void onAttach(Activity activity) {
Log.d(TAG,"onAttach");
super.onAttach(activity);
try {
mCallback = (OnLoggedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLoggedListener in order to use this fragment");
}
}
#Override
public void onResume() {
Log.d(TAG,"onResume");
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
mFbSdkUiHelper.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
Log.d(TAG,"onPause");
super.onPause();
mFbSdkUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mFbSdkUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
mFbSdkUiHelper.onSaveInstanceState(outState);
}
}
LogCat
D/com.example.sample.FragmentA3 ﹕ onAttach
D/com.example.sample.FragmentA3 ﹕ onCreate
D/com.example.sample.FragmentA3 ﹕ onCreateView
D/com.example.sample.FragmentA3 ﹕ onResume
D/dalvikvm ﹕ GC_FOR_ALLOC freed 764K, 10% free 7977K/8816K, paused 3ms, total 6ms
W/GooglePlayServicesUtil ﹕ Google Play services is missing.
D/com.example.sample.FragmentA3 ﹕ onPause
D/com.example.sample.FragmentA3 ﹕ onSessionStateChange
W/EGL_emulation ﹕ eglSurfaceAttrib not implemented
I/Choreographer ﹕ Skipped 174 frames! The application may be doing too much work on its main thread.
D/com.example.sample.MainActivity﹕ onActivityResult
D/com.example.sample.FragmentA ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onActivityResult
D/com.example.sample.FragmentA3 ﹕ onResume
Please try this solution:
public class FragmentA3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Fragment fragmentA1 = this.getParentFragment();
Fragment fragmentA = fragmentA1.getParentFragment();
loginButton.setFragment(fragmentA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
mFbSdkUiHelper.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA1 extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA3 !=null)
mFragmentA3.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
public class FragmentA extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mFragmentA1 !=null)
mFragmentA1.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
Step 1: Add the below code in the fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
context = getContext();
FacebookSdk.sdkInitialize(context);
View view = inflater.inflate(R.layout.fragment_facebook_sign_in, container, false);
}
Step 2: Handle the callback of facebook.
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = object.getString("email");
String firstName = object.getString("first_name");
String lastName = object.getString("last_name");
profile_link = object.getString("link");
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
Utility.logMe("\nFacebook_user_mail:"+email +"\nFacebook_user_Fname:"+firstName+"\nFacebook_user_Lname:"+lastName+"\nFacebook_user_Image:"+profilePicUrl+"\nProfile_link:"+profile_link);
if(email != null && email.length()> 0)
{
LoginManager.getInstance().logOut();
signUpFacebook(firstName, lastName, email, profilePicUrl, profile_link);
}
else {
Toast.makeText(getActivity(), "Email not present to login", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Email Not Exist for this user on Facebook.", Toast.LENGTH_LONG).show();
progressDialog = new ProgressDialog(getContext());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,link,name,email,birthday,gender,first_name,last_name,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
Step 3:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
//displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
Step 4:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
Step 5:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Step 6:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
for (Fragment fragmento : allFragments) {
if (fragmento instanceof TwitterSignIn) {
((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof GooglePlusSignIn) {
((GooglePlusSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
if (fragmento instanceof FacebookSignIn) {
((FacebookSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
}
}
}

Using ZXing in Activity with Fragment does not work

In my App I have a MainActivity, which makes use of different fragments. One of these fragments is kind of a detail fragment, where I want to capture some serials by scanning a QR code. Currently, I am trying to use the IntentIntegrator. I am able to scan the code successfully, but after that, my App is not returning correctly. It just displays my MainActivity, but there is no Toast.
I also tried to put a onActivityResult() in the fragment and a super.onActivityResult()in the activities onActivityResult() but it is always the same behaviour. It just jumps into the MainActivity and nothing futher happens.
Can somebody exlain to me, where I made the mistakes? I want to scan the barcode and get the results in my fragment class.
Here is my MainActivity Code:
public class MainActivity extends Activity {
private Button startenButton, ansehenButton, abmeldenButton;
private FrameLayout fragmentFrame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentFrame = (FrameLayout) findViewById(R.id.frameLayout);
startenButton = (Button) findViewById(R.id.buttonPruefungStart);
startenButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (fragmentFrame.getChildCount() < 1) {
transaction.add(R.id.frameLayout, new PruefungStartenFragment());
} else {
transaction.replace(R.id.frameLayout, new PruefungStartenFragment());
}
transaction.commit();
}
});
}
public void scan() {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
Toast.makeText(this, scanResult.getContents(), Toast.LENGTH_LONG).show();
}
}
}
And here is my PruefungStartenFragment Code:
public class PruefungStartenFragment extends Fragment {
private TextView datum, ort, pruefer, bedienerdisplay, scanner, fingerprintscanner, quittungsdrucker, barcodeleser,
webcam, kundendisplay, terminal;
private Button scanButton, startButton;
public static PruefungStartenFragment newInstance(String code) {
Bundle args = new Bundle();
args.putSerializable("code", code);
PruefungStartenFragment fragment = new PruefungStartenFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pruefung_starten_fragment, container, false);
scanButton = (Button) v.findViewById(R.id.buttonScan);
scanButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).scan();
}
});
return v;
}
}
I figured out my problem... In my manifest I had a android:noHistory="true" in my MainActivity. This prevents the scanning activity in the barcode scanner to pass the result to my MainActivity, because there is no activity on the stack, where it could pass results to.

Categories

Resources