Progressbar is not displaying in fragment - java

I have created a Firebase application.
Everything so far is working great. I have one issue, however, that I'm unable to fix.
My MainActivity.java is implementing an Interface ProgressDisplay.java
The Interface has two methods:
public interface ProgressDisplay {
public void showProgress();
public void hideProgress();
}
I'm not able to call these 2 methods from sub fragments, I'm unable to set the visibility on and off in the fragments.
ManageAccountFragment.java
package com.company.walt.fragments;
public class ManageAccountFragment extends Fragment {
private EditText mName;
private Button mUpdateBtn;
private ProgressBar mProgressBar;
public ManageAccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_manage_account, container, false);
mName = (EditText)view.findViewById(R.id.input_name);
mUpdateBtn = (Button)view.findViewById(R.id.btn_update);
mUpdateBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view){
if (!isEmpty (mName.getText().toString()))
{
showProgress();
Toast.makeText(getActivity(), "SHOW DIALOG", Toast.LENGTH_SHORT).show();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(mName.getText().toString())
//.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
}
}
});
hideProgress();
Toast.makeText(getActivity(), "HIDE DIALOG", Toast.LENGTH_SHORT).show();
}
}
}
});
hideSoftKeyboard();
return view;
}
private boolean isEmpty(String string){
return string.equals("");
}
/**
* Display progressbar
*/
protected void showProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).showProgress();
}
}
/**
* Hide progressbar
*/
protected void hideProgress() {
if (getActivity() instanceof ProgressDisplay) {
((ProgressDisplay) getActivity()).hideProgress();
}
}
private void hideSoftKeyboard(){
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
MainActivity.java
package com.company.walt.activities;
public class MainActivity extends AppCompatActivity implements ProgressDisplay {
private static final String TAG = "MainActivity";
private static final int USER_PROFILE = 1;
private static final int PROFILE_MANAGE = 2;
private static final int PROFILE_SETTING = 3;
private Toolbar mainToolbar;
private AccountHeader headerResult = null;
private Drawer result = null;
private ProgressBar mProgressBar;
private ToggleButton switcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) { setTheme(R.style.NightTheme); }
else { setTheme(R.style.LightTheme);}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchAppTheme();
createToolbar();
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
buildHeader(false, savedInstanceState);
createDrawerBuilder();
getUserDetails();
}
#Override
protected void onResume() {
super.onResume();
checkAuthenticationState();
}
/**
* Used to check if user is authenticated or not
*/
private void checkAuthenticationState()
{
Log.d(TAG, "checkAuthenticationState: checking authentication state.");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null){
Log.d(TAG, "checkAuthenticationState: user is null, navigating back to login screen.");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else {
Log.d(TAG, "checkAuthenticationState: user is authenticated.");
}
}
/**
* Used to switch between light and dark mode
*/
public void switchAppTheme() {
switcher = (ToggleButton) findViewById(R.id.switcher);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
switcher.setChecked(true);
}
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
restartApp();
} else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
restartApp();
}
}
});
}
/**
* Used to create the toolbar on top
*/
private void createToolbar(){
mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(R.string.app_name);
}
/**
* small helper method to reuse the logic to build the AccountHeader
* this will be used to replace the header of the drawer with a compact/normal header
*
* #param compact
* #param savedInstanceState
*/
private void buildHeader(boolean compact, Bundle savedInstanceState) {
IProfile profile_1;
//IProfile profile_2;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
profile_1 = new ProfileDrawerItem()
.withName(name)
.withEmail(email)
.withIcon(photoUrl);
//profile_2 = new ProfileDrawerItem().withName("Isensei").withEmail("itrade#gmail.com").withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.ip_menu_header_bg)
.withCompactStyle(compact)
.addProfiles(
profile_1,
//profile_2,
new ProfileSettingDrawerItem()
.withName("Manage Account")
.withDescription("Manage your details")
.withIcon(new IconicsDrawable(this,GoogleMaterial.Icon.gmd_settings)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_MANAGE),
new ProfileSettingDrawerItem()
.withName("Add Account")
.withDescription("Register new account")
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_person_add)
.actionBar().colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_SETTING)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
//sample usage of the onProfileChanged listener
//if the clicked item has the identifier 1 add a new profile ;)
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == USER_PROFILE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new HomeFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_MANAGE)
{
// Navigate to home fragment
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
fragment = new ManageAccountFragment();
transaction.replace(R.id.flContent, fragment);
transaction.commit();
}
else if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING)
{
Toast.makeText(MainActivity.this, "ACCOUNT", Toast.LENGTH_SHORT).show();
}
/*
if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
IProfile newProfile = new ProfileDrawerItem()
.withNameShown(true)
.withName("Kensei")
.withEmail("kensei#gmail.com")
.withIcon(getResources().getDrawable(R.drawable.ic_user_58dp));
if (headerResult.getProfiles() != null) {
//we know that there are 2 setting elements. set the new profile above them ;)
headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
} else {
headerResult.addProfiles(newProfile);
}
}
*/
//false if you have not consumed the event and it should close the drawer
return false;
}
})
.build();
}
}
/**
* Used to create the drawer with all the icons and items
*/
private void createDrawerBuilder(){
//create the drawer and remember the `Drawer` result object
result = new DrawerBuilder()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(mainToolbar)
.addDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_services)
.withIdentifier(1)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_products)
.withIdentifier(2)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_photos)
.withIdentifier(3)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_poem)
.withIdentifier(4)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_content_copy))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_archives)
.withIdentifier(5)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_folder_open))
.withTag("Bullhorn"),
new SectionDrawerItem().withName(R.string.drawer_section_header).withEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_settings)
.withIdentifier(6)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_feedback)
.withIdentifier(7)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_headset_mic))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_pro)
.withIdentifier(8)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_security))
.withTag("Bullhorn"),
new SecondaryDrawerItem().withName(R.string.drawer_logout)
.withIdentifier(9)
.withIconTintingEnabled(true)
.withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_power_settings_new))
.withTag("Bullhorn")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
navigateDrawerItem((int)drawerItem.getIdentifier(), drawerItem);
return true;
}
})
.addStickyDrawerItems(
new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
).build();
}
/**
* Used to navigate to drawer fragment items
*/
public void navigateDrawerItem(int ItemId, IDrawerItem drawerItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(ItemId) {
case 1:
fragmentClass = ServicesFragment.class;
break;
case 2:
fragmentClass = ProductsFragment.class;
break;
case 3:
fragmentClass = PhotosFragment.class;
break;
case 4:
fragmentClass = PoemsFragment.class;
break;
case 5:
fragmentClass = ArchivesFragment.class;
break;
case 6:
fragmentClass = SettingsFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
result.closeDrawer();
}
/*
private void setUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName("Jsk Zack")
.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: User Profile updated");
getUserDetails();
}
}
});
}
}
*/
private void getUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null)
{
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
String properties =
"uid: " + uid + "\n" +
"name: " + name + "\n" +
"email: " + email + "\n" +
"photoUrl: " + photoUrl;
Log.d(TAG, "getUserDetails: properties: \n" + properties);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
//add the values which need to be saved from the accountHeader to the bundle
outState = headerResult.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
/**
* Display progressbar
*/
public void showProgress() {
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
}
/**
* Hide progressbar
*/
public void hideProgress() {
if(mProgressBar.getVisibility() == View.VISIBLE){
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
}
}
/**
* Used to relaunch the application
*/
public void restartApp() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
I don't know why this is not working, am I doing something wrong?

I think its because of this lines of code
findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
Just instantiate your Progressbar in your main Activity onCreate(){HERE} and use mProgressBar in the Hide and Show functions
public void showProgress() {
mProgressBar .setVisibility(View.VISIBLE);
}
I Hope this helps ;)

Related

Android Activity is restarting multiple times in a loop in android studio

Email login activity allows user to log in to his account. here , after the user is logged in , he will be sent to main activity using the main activity intent. here as soon as the user is logged in to the account , he is sent to main activity , and the main activity is restating continously . the screen recording video is uploaded in the link mentioned "https://drive.google.com/file/d/1QRy2J1YkMRJdbjgMIIl-T58DsGnamtGX/view?usp=sharing"
here is the "LOGCAT"
1650989781.030 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.184 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971948, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=9033321453691971949}]
1650989781.193 22200-22200/com.example.indiatalks I/InputTransport: Create ARC handle: 0x7d16279460
1650989781.263 22200-22231/com.example.indiatalks V/FA: Activity resumed, time: 629575044
1650989781.437 22200-22231/com.example.indiatalks V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 264
1650989781.439 22200-22231/com.example.indiatalks V/FA: Activity paused, time: 629575308
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: applied 1 plugins for [com.example.indiatalks]:
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: plugin 1: [libMEOW_gift.so]:
1650989781.687 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.777 22200-22225/com.example.indiatalks I/mple.indiatalk: Waiting for a blocking GC ProfileSaver
1650989781.830 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971949,
public class MainActivity extends AppCompatActivity {
private ImageButton AddNewPostButton, ChatListButton;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef, PostsRef;
private ProgressDialog loadingBar;
public ImageButton selectPostButton;
private Button UpdatePostButton, WritePost;
private EditText PostDescription;
private static final int GalleryPick = 100;
private Uri ImageUri;
private String checker = "";
private String Description;
private StorageReference PostsReference;
private DatabaseReference UsersRef;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadurl, currentUserid, userName;
private Toolbar mToolbar;
private CircleImageView navProfileImage;
private TextView navUserName;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ViewPager myNewsFeedViewpager;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private BottomNavigationView BottomNavMenu;
private RecyclerView postsLists;
private RecyclerView.LayoutManager newsFeedsLinearlayoutManager;
private PostsAdapter postsAdapter;
private final List < Posts > postsArraylist = new ArrayList < > ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
RootRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.explore_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Boww Talks");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (currentUser == null) {
SendUserToLoginActivity();
} else {
updateUserStatus("online");
VerifyUserExistence();
}
IntializeControllers();
drawerLayout = (DrawerLayout) findViewById(R.id.drawyer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
navUserName = (TextView) navView.findViewById(R.id.nav_profile_name);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem Item) {
NavMenuSelector(Item);
return false;
}
});
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
return true;
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent MyaddPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(MyaddPostIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_alert)
{
Intent NotificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
overridePendingTransition(0, 0);
startActivity(NotificationIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_profile)
{
Intent MyProfileIntent = new Intent(MainActivity.this, settingsActivity.class);
overridePendingTransition(0, 0);
startActivity(MyProfileIntent);
return true;
}
return false;
}
});
BottomNavMenu.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
Intent MyMainIntent = new Intent(MainActivity.this, MainActivity.class);
overridePendingTransition(0, 0);
startActivity(MyMainIntent);
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent addPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(addPostIntent);
}
if (menuItem.getItemId() == R.id.ic_alert)
{
}
}
});
ChatListButton = (ImageButton) findViewById(R.id.chat_list_button);
ChatListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Intent = new Intent(MainActivity.this, ChatListActivity.class);
startActivity(Intent);
}
});
}
#Override
protected void onRestart() {
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
super.onRestart();
}
private void NavMenuSelector(MenuItem Item) {
switch (Item.getItemId()) {
case R.id.BirthDays:
Toast.makeText(this, "Birthdays selected", Toast.LENGTH_SHORT).show();
break;
case R.id.shortClips:
Toast.makeText(this, "Short Clips selected", Toast.LENGTH_SHORT).show();
break;
case R.id.short_Films:
Toast.makeText(this, "ShortFilms selected", Toast.LENGTH_SHORT).show();
break;
case R.id.marketing:
Toast.makeText(this, "Marketing selected", Toast.LENGTH_SHORT).show();
break;
case R.id.Find_Friends_option:
Toast.makeText(this, "Find Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.my_contacts:
Toast.makeText(this, "My Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.privacy_Settings_option:
Toast.makeText(this, "Privacy Settings selected", Toast.LENGTH_SHORT).show();
break;
case R.id.main_Log_Out_option:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
private void IntializeControllers() {
postsAdapter = new PostsAdapter(postsArraylist);
postsLists = (RecyclerView) findViewById(R.id.news_feeds);
postsLists.setHasFixedSize(true);
newsFeedsLinearlayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
postsLists.setLayoutManager(newsFeedsLinearlayoutManager);
postsLists.setAdapter(postsAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
if (currentUser != null) {
updateUserStatus("offline");
}
}
private void updateNewsFeeds() {
PostsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Posts posts = dataSnapshot.getValue(Posts.class);
postsArraylist.add(posts);
postsAdapter.notifyDataSetChanged();
postsAdapter.notifyDataSetChanged();
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
postsAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateNavMenu() {
currentUserid = currentUser.getUid();
UsersRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
} else {
navUserName.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "Set profile NAVIGATION", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void VerifyUserExistence() {
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
updateNavMenu();
updateNewsFeeds();
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
updateNavMenu();
updateNewsFeeds();
navUserName.setText(retrieveUserName);
} else if ((dataSnapshot.child("name").exists())) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
updateNavMenu();
updateNewsFeeds();
} else {
SendUserTosettingsActivity();
Toast.makeText(MainActivity.this, "Update your profile for settings!!!!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateUserStatus(String state) {
String saveCurrentTime, saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime = currentTime.format(calendar.getTime());
HashMap < String, Object > onlineStateMap = new HashMap < > ();
onlineStateMap.put("time", saveCurrentTime);
onlineStateMap.put("date", saveCurrentDate);
onlineStateMap.put("state", state);
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).child("userOnlineState")
.updateChildren(onlineStateMap);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserTosettingsActivity() {
Intent settingsIntent = new Intent(MainActivity.this, settingsActivity.class);
startActivity(settingsIntent);
}
private void SendUserToFIndFriendsActivity() {
Intent findfriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
startActivity(findfriendsIntent);
}
private void SendUserToMyProfileActivity() {
Intent MyProfileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(MyProfileIntent);
}
}
public class emailloginActivity extends AppCompatActivity
{
private EditText UserEmail,UserPassword;
private TextView ForgotPasswordLink;
private Button LoginButton ,NeedNewAccount;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private DatabaseReference UsersRef;
private FirebaseUser currentUser;
public emailloginActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emaillogin);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = mAuth.getCurrentUser();
LoginButton = (Button) findViewById(R.id.login_button);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AllowUserToLogin();
}
});
InitializeFields();
NeedNewAccount.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SendUserToRegisterActivity();
}
});
}
#Override
protected void onPause() {
if (loadingBar != null) {
loadingBar.dismiss();
}
super.onPause();
}
private void AllowUserToLogin()
{
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please Enter Email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Sign in");
loadingBar.setMessage("Please wait........");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
}
{
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
String currentUserId = mAuth.getCurrentUser().getUid();
String deviceToken = FirebaseInstanceId.getInstance().getToken();
UsersRef.child(currentUserId).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
VerifyUserExistence();
Toast.makeText(emailloginActivity.this, "Welcome!!!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(emailloginActivity.this, "Roasted!!!: Check the Email Id and Password", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields()
{
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccount = (Button) findViewById(R.id.Need_new_Account_button);
LoginButton = (Button) findViewById(R.id.login_button);
ForgotPasswordLink = (TextView) findViewById(R.id.Forgot_password);
loadingBar = new ProgressDialog(this);
}
private void VerifyUserExistence ()
{
String userName = mAuth.getCurrentUser().getUid();
UsersRef.child(userName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())&& (dataSnapshot.hasChild("name"))) {
SendUserToMain();
loadingBar.dismiss();
finish();
}
else
{
SendUserTosettingsActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserTosettingsActivity()
{
Intent mainIntent = new Intent(emailloginActivity.this , settingsActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent MainIntent = new Intent(emailloginActivity.this, MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("mUserID" , userName );
finish();
startActivity(MainIntent);
}
private void SendUserToRegisterActivity()
{
Intent RegisterIntent = new Intent(emailloginActivity.this, RegisterActivity.class);
startActivity(RegisterIntent);
}
}
Mistake is here that you called finish(); before calling startActivity(MainIntent);. Use camelCaseinstade of Capital case in defining variable.
Make changes in your emailloginActivity as below
// changed from MainIntent to mIntent.
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent mIntent = new Intent(emailloginActivity.this, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("mUserID" , userName );
startActivity(mIntent);
finish();
}

Android could not lock surface when puting shared preferences

Very strange thing. I found out that when I do spEditor.putBoolean("closePxCmInfo", false).apply(); then an error occurs like that:
2022-01-03 10:47:39.761 3821-3917/? E/ViewRootImpl#6827b15[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.774 3821-3917/? E/ViewRootImpl#f395385[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.792 3821-3917/? E/ViewRootImpl#24f27f5[mierzenieopencv]: Surface is not valid.
2022-01-03 10:47:39.820 13383-13710/pl.jawegiel.mierzenieopencv E/OpenCV/StaticHelper: OpenCV error: Cannot load info library for OpenCV
2022-01-03 10:47:39.824 3335-3449/? E/BufferQueueProducer: [Splash Screen pl.jawegiel.mierzenieopencv[13383]#0] connect: BufferQueue has been abandoned
2022-01-03 10:47:39.824 3821-3917/? E/ViewRootImpl#4fd5d5c[mierzenieopencv]: Could not lock surface
java.lang.IllegalArgumentException
at android.view.Surface.nativeLockCanvas(Native Method)
at android.view.Surface.lockCanvas(Surface.java:345)
at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:4018)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:3979)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3721)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3029)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1888)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8511)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:696)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:65)
at com.android.server.ServiceThread.run(Unknown Source:12)
It has nothing to do with my lauout I tested it out. The problem is with this line that I mentioned about putting shared preference.
Here is my code:
Stages.java
public class Stages extends BaseActivity {
private final Stage0StageFragment stageZeroFragment = new Stage0StageFragment();
private final Stage1StageFragment stageOneFragment = new Stage1StageFragment();
private final Stage2StageFragment stageTwoFragment = new Stage2StageFragment();
private final Stage3StageFragment stageThreeFragment = new Stage3StageFragment();
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
OnSwitchFragmentFromStageTwo onSwitchFragmentFromStageTwo;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Util.setThemeBasedOnPrefs(this);
setContentView(R.layout.stages);
spEditor.putBoolean("closePxCmInfo", false).apply(); // HERE IS THE PROBLEM
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnNavigationItemSelectedListener(item -> {
if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_zero) {
if (!sp.getBoolean("correctionDone", false)) {
AlertDialog alertDialog = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_info, R.string.hide_dialog_title, getString(R.string.stage_zero_confirmation), (dialog, which) -> {
spEditor.putBoolean("correctionDone", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
alertDialog.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(alertDialog));
alertDialog.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} else if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_two) {
try {
if (onSwitchFragmentFromStageTwo.onSwitchFragmentFromFragmentTwo() <= 0.5 && !sp.contains("closePxCmInfo")) {
AlertDialog ad = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_alert, R.string.hide_dialog_title_alert, getResources().getString(R.string.benchmark_not_drawn), (dialog, which) -> {
spEditor.putBoolean("closePxCmInfo", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
ad.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(ad));
ad.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
showFragment(item.getItemId());
}
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (!sp.getBoolean("correctionDone", false))
ft.replace(R.id.content_frame, stageZeroFragment);
else {
ft.replace(R.id.content_frame, stageOneFragment);
bottomNavView.setSelectedItemId(R.id.navigation_stage_one);
}
ft.commit();
}
#Override
BaseActivity getActivity() {
return this;
}
private void setAlertDialogButtonsAttributes(AlertDialog alertDialog2) {
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
params.setMargins(10, 0, 10, 0);
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setLayoutParams(params);
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setLayoutParams(params);
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.navigation_stage_zero:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_zero) {
fragment = stageZeroFragment;
newPosition = 0;
}
break;
case R.id.navigation_stage_one:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_one) {
fragment = stageOneFragment;
newPosition = 1;
}
break;
case R.id.navigation_stage_two:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_two) {
fragment = stageTwoFragment;
newPosition = 2;
}
break;
case R.id.navigation_stage_three:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_three) {
fragment = stageThreeFragment;
newPosition = 3;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
}
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity {
SharedPreferences sp;
SharedPreferences.Editor spEditor;
BaseActivity childActivity;
#Override
#SuppressWarnings("CommitPrefEdits")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = PreferenceManager.getDefaultSharedPreferences(BaseActivity.this);
spEditor = sp.edit();
childActivity = getActivity();
if(childActivity instanceof MainActivity)
MobileAds.initialize(this, initializationStatus -> {});
}
#Override
protected void onPause() {
if (childActivity instanceof Stages) {
spEditor.putFloat("px_cm", 0f);
spEditor.putFloat("rozmiar_px", 0f);
spEditor.putFloat("rozmiar_px_x", (float) 0f);
spEditor.putFloat("rozmiar_px_y", (float) 0f);
spEditor.apply();
}
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (childActivity instanceof Stages) {
getMenuInflater().inflate(R.menu.main, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (childActivity instanceof Stages)
return Util.onOptionsItemSelected(this, item);
else
return false;
}
#Override
public void onBackPressed() {
if (childActivity instanceof Stages) {
Intent intent = new Intent(childActivity, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
super.onBackPressed();
}
abstract BaseActivity getActivity();
}
Help me please!

save url when re rotate screen from landscape to protrit

I'm trying to play video on player and the video is url that I fetch from an api
so I have a channels in recycleview1 and when I click on one channel the channel start play in new activity
in that activity the player take half of screen and the rest is for recycleview2 which contain some channels for easy and fast navigate between channels
so when I open the channel from recycleview1 and it start playing then I rotate the screen to landscape it work fine then restore the screen to portrate again the channel still working
but the problem is when I click on channel from recycleview2 which lead to update the url that already played and start the new one
so each time I click on channel from recycleview2 the videoview updated to new channel url that clicked
I face problem when I rotate the screen after played channel from recycleview2 the videoview start play a channel that I clicked from recyclewview1 before clicking on new channel from recycleview2 because it return to onCreate method which build the url depend on the information passed with on click
so I used to save the instance state of url so when I rotate the screen to landscape the vidoeview still played the last channel that played
but the problem is when I re rotate the screen to portrate again the videoview here return to the first channel played when start the activity
I tried to save instance state too but it doesn't working
this is the code:
public class TVChannel extends AppCompatActivity implements
TVAdapter.TVAdapterOnClickHandler {
private VideoView videoView;
private int position = 0;
private String video;
private MediaController mediaController;
String mChannelTitle;
String mChannelApp;
String mChannelStreamname;
String mChannelCat;
TVAdapter mAdapter;
RecyclerView mSportsList;
private TextView mCategory;
private TextView mErrorMessageDisplay;
private ProgressBar mLoadingIndicator;
Context mContext ;
public TVItem channelObject;
Uri vidUri;
String myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_tv_channel);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapper();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
} else {
setContentView(R.layout.activity_tv_channel2);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(false);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.controlBackground));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapperFullScreen();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putString("video", String.valueOf(vidUri));
videoView.start();
}
// After rotating the phone. This method is called.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
video = savedInstanceState.getString("video");
videoView.start();
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel, View view) {
if (channel != null) {
mChannelTitle = String.valueOf(channel.getTitle());
mChannelApp = String.valueOf(channel.getApp());
mChannelStreamname = String.valueOf(channel.getStreamName());
}
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(playerControlView.getMediaControllerWrapper());
//
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
}
private void showTVDataView() {
mErrorMessageDisplay.setVisibility(View.INVISIBLE);
mSportsList.setVisibility(View.VISIBLE);
}
private void showErrorMessage() {
mSportsList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(TVChannel.this, jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
mCategory.setText(TVData.get(0).getCat());
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
showErrorMessage();
}
}
}
}
you can see that I use:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
}
else{
}
to set content view for portrait and landscape
and inside else this is the code that I use to save the url in landscape mode:
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
and if savedInstanceState null so build url like this from on click information that I pass in portrait mode:
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
how can I save the url channel when I re rotate screen from landscape to portrait mode again?

(Android) Starting up a fragment is blocking LocationListener

So when I comment out past the facebook code comment, the Location manager does work and onLocationChanged does update the proper Latitude and Longitude. However, when I uncomment it, the Facebook functionality works but the onLocationChanged never gets called for some reason.
MainActivity.java
public class MainActivity extends FragmentActivity implements OnClickListener {
private MainFragment mainFragment;
Button sendIPbutton; //Button for sending IP Address
EditText mEdit; //Get info from what user enters in form
//TextView mText;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/*/
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
/**************************Facebook code********************************************/
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
/*********************************************************************************/
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude();
// Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
coordinates = (TextView)findViewById(R.id.coordinates);
coordinates.setText(Text);
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}/* End of Class MyLocationListener */
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void setObject(View view){
Intent intent = new Intent(this, SetObjectActivity.class);
startActivity(intent);
}
I think there must be something going on in the oncreate function.
Here is my MainFragment.java code. Note that it's primarily from the Facebook Login and Sharing tutorial on their website.
public class MainFragment extends Fragment {
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private static final String TAG = MainFragment.class.getSimpleName();
private TextView coordinates;
private UiLifecycleHelper uiHelper;
private final List<String> permissions;
public MainFragment() {
permissions = Arrays.asList("user_status");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
shareButton = (Button) view.findViewById(R.id.shareButton);
coordinates = (TextView) view.findViewById(R.id.coordinates);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(permissions);
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
String text = coordinates.getText().toString();
Bundle postParams = new Bundle();
postParams.putString("name", "My Location!");
postParams.putString("caption", "Thanks to Hot and Cold");
postParams.putString("description", text);
postParams.putString("link", null);
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
}
So apparently I was spot on about the Fragment causing the issue. to Resolve it, I just added Context to the fragment class, i imported all of the Location logic into MainFragment, and now it works!

RuntimeException : android.view.InflateException: Binary XML file line #8: Error inflating class fragment

I want to integrate my Google map with Facebook SDK to check in location via Facebook and share it out in the same layout but when I add this code to method onCreate(), it's force close and tell an errors
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
myFragmentManager = getSupportFragmentManager();
mainFragment = (MainFragment) myFragmentManager.findFragmentById(R.id.checkIn);
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
and here is my onCreate() method
protected void onCreate(final Bundle savedInstanceState) {
try {
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.check_in);
checkInButton = (Button) findViewById(R.id.shareButton);
checkInButton.setVisibility(View.VISIBLE);
authButton = (Button)findViewById(R.id.authButton);
authButton.setVisibility(View.VISIBLE);
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.INVISIBLE);
toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (hasConnection(getApplicationContext()) == true) {
if (toggle.isChecked()) {
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.VISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.INVISIBLE);
goButton.setVisibility(View.VISIBLE);
} else {
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.VISIBLE);
goButton.setVisibility(View.VISIBLE);
}
checkInButton.setVisibility(View.VISIBLE);
checkInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
endLocationEditText
.setVisibility(View.INVISIBLE);
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Attach photo?");
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
captureIntent,
CAMERA_CAPTURE);
}
});
builder.show();
}
});
} else {
System.out.println("ยังไม่ได้ต่อเน็ต");
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Please connect to the Internet.");
builder.show();
}
}
});
goButton = (Button) findViewById(R.id.goButton);
goButton.setVisibility(View.INVISIBLE);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (toggle.isChecked() == true) {
String location = endLocationEditText.getText()
.toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
} else {
String location = startLocationEdittext.getText()
.toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
}
});
myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = myLocationManager.getBestProvider(criteria, true);
Location location = myLocationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 20000, 0, this);
// สำหรับแสดง Google maps v2
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager
.findFragmentById(R.id.checkIn);
myMap = mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
fromMarkerPosition = new LatLng(location.getLatitude(),
location.getLongitude());
toMarkerPosition = fromMarkerPosition;
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
fromMarkerPosition, 13));
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.addMarker(new MarkerOptions()
.position(fromMarkerPosition)
.title("Yor are here!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setZoomControlsEnabled(true);
/* จบการแสดง maps */
// สร้าง click event สำหรับระบุพิกัดจุด
myMap.setOnMapClickListener(new OnMapClickListener() {
public void onMapClick(LatLng arg0) {
if (hasConnection(getApplicationContext()) == true) {
final LatLng coordinate = arg0;
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext.setVisibility(View.INVISIBLE);
goButton.setVisibility(View.INVISIBLE);
System.out
.println("#####################################################");
builder.setTitle("Select Marker").setItems(
new String[] { "From", "To" },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int position) {
try {
if (position == 0) {
fromMarkerPosition = coordinate;
System.out
.println(fromMarkerPosition
+ " yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
refreshMarker();
} else if (position == 1) {
toMarkerPosition = coordinate;
System.out
.println(toMarkerPosition
+ " ttttttttttttttttttttttttttttttttttttttt");
refreshMarker();
}
} catch (Exception ex) {
ex.printStackTrace();
System.out
.println("Please connect to the internet first");
}
}
});
builder.show();
myMap.animateCamera(CameraUpdateFactory
.newLatLng(coordinate));
checkInButton.setVisibility(View.VISIBLE);
checkInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
endLocationEditText
.setVisibility(View.INVISIBLE);
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Attach photo?");
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
captureIntent,
CAMERA_CAPTURE);
}
});
builder.show();
}
});
} else {
System.out.println("ยังไม่ได้ต่อเน็ต");
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Please connect to the Internet.");
builder.show();
}
}
});
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
myFragmentManager = getSupportFragmentManager();
mainFragment = (MainFragment) myFragmentManager
.findFragmentById(R.id.checkIn);
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}// end onCreate
here is my MainFragment class........
public class MainFragment extends Fragment{
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private Button shareButton;
private UiLifecycleHelper uiHelper;
private static final String TAG = "MainFragment";
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.check_in, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
}
xml line 8 is here
<fragment
android:id="#+id/checkIn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/authButton"
class="com.google.android.gms.maps.SupportMapFragment" />
here is an Errors
03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f04000a, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
Take a look at http://code.google.com/p/gmaps-api-issues/issues/detail?id=5064#c1 for how to put SupportMapFragment inside fragment correctly.

Categories

Resources