john john john john - 6 months ago 22
Android Question

Android : Link Fragment to Activity

I have the following fragment:

public class LoginFragment extends Fragment {

private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private static final String TAG = "LoginFragment";

private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));

}


@Override
public void onCancel() {
Log.d(TAG, "onCancel");
}

@Override
public void onError(FacebookException e) {
Log.d(TAG, "onError " + e);
}
};


public LoginFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();

mTokenTracker.startTracking();
mProfileTracker.startTracking();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login_button, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setupTextDetails(view);
setupLoginButton(view);
}

@Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}

@Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

private void setupTextDetails(View view) {
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}

private void setupTokenTracker() {
mTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Log.d(TAG, "" + currentAccessToken);
}
};
}

private void setupProfileTracker() {
mProfileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Log.d(TAG, "" + currentProfile);
mTextDetails.setText(constructWelcomeMessage(currentProfile));
}
};
}

private void setupLoginButton(View view) {
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
mButtonLogin.setFragment(this);
mButtonLogin.setCompoundDrawables(null, null, null, null);
mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}

private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
return stringBuffer.toString();
}
}


and the following MainActivity.class:

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

private ListAdapter listAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);



setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

// Add sample data to event list.
ListView listView = (ListView) findViewById(R.id.listView);
listAdapter = TestData.getEventListAdapter(this);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: Navigate to event detail page.
}
});


}


@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {

} else if (id == R.id.nav_slideshow) {

} else if (id == R.id.nav_manage) {

} else if (id == R.id.nav_share) {

} else if (id == R.id.nav_send) {

}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}


And AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xx.xx.xx" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />

<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>

<activity
android:name=".EventCreate"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".EventCreate" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>

</application>
</manifest>


As I have read, in Android Manifest I cannot add fragments. So I am trying to use my LoginFragment class as Launcher because I want the application to start with the Facebook Login Button first. Somehow, I have to use the Fragment Manager but I don't know how.

Can someone demonstrate how I can solve this case?

Answer

Add LoginActivity to hold LoginFragment and if user successfully login proceed to MainActivity.

public static class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.login_activity_layout);

        LoginFragment loginFragment = new LoginFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.your_container, loginFragment).commit();

    }
}

login_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/your_container"
    android:orientation="horizontal">

</LinearLayout>

In your LoginFragment start your MainActivity by intent.

private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.d(TAG, "onSuccess");
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        mTextDetails.setText(constructWelcomeMessage(profile));

        Intent intent = new Intent(getActivity(), MainActivity.class);
        startActivity(intent);
    }


    @Override
    public void onCancel() {
        Log.d(TAG, "onCancel");
    }

    @Override
    public void onError(FacebookException e) {
        Log.d(TAG, "onError " + e);
    }
};