Mapbox SDK in Android Fragment - java

I want to show mapbox mapview in fragment but i cant do that. I looked lots of problems and solutions however i cant solve my issue. App is crashing always. BottomNavigation class is main class, MapFragment is fragment class which i want to see map. Also i attached Xml codes. Thank you!
BottomNavigation.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class BottomNavigation extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
loadFragment(new MapFragment());
}
private boolean loadFragment(Fragment fragment){
if (fragment != null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()){
case R.id.navigation_map:
fragment = new MapFragment();
break;
case R.id.navigation_search:
fragment = new SearchFragment();
break;
case R.id.navigation_event:
fragment = new EventsFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
}
MapFragment.java
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
public class MapFragment extends Fragment {
private MapView mapView;
public MapFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map,container,false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(new Style.Builder().fromUrl("mapbox://styles/orucbe/cjqnneisv0gns2ro1fy83ucgl"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(41.885, -87.679)) // set the camera's center position
.zoom(12) // set the camera's zoom level
.tilt(20) // set the camera's tilt
.build();
// Move the camera to that position
mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
activity_bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BottomNavigation">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="56dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
>
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</com.mapbox.mapboxsdk.maps.MapView>
</android.support.constraint.ConstraintLayout>

Problem is that there is no setted access token. Access token should be set before inflating. That's all.
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
public class MapFragment extends Fragment {
private MapView mapView;
public MapFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Mapbox.getInstance(getContext().getApplicationContext(),"access_token");
View view = inflater.inflate(R.layout.fragment_map,container,false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(new Style.Builder().fromUrl("style_url"));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
}
}

Related

Cannot see Mapbox map on the screen

I'm trying to implement Mapbox map to my project where i use Fragments.
Here is MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MainMenu()).commit();
}
}
}
activity_main.xml:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
MainMenu.java (Fragment where i'm trying to show the map):
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
public class MainMenu extends Fragment {
private MapView mapView;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_menu, container, false);
Mapbox.getInstance(getContext().getApplicationContext(), getString(R.string.access_token));
mapView = rootView.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
return rootView;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
}
And my main_menu.xml file:
(I'm using RelativeLayout and CoordinatorLayout here. I won't past all the code, only beginning)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="37.7749"
mapbox:mapbox_cameraTargetLng="-122.4194"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12"
/>
I only have one error in Logcat, but I don't think that's the source of the problem (sorry if I'm wrong). I'll attach screenshot of the error and emulator below
Error
Screen of the emulator
The app doesn't crash, I just can't see the map.
Thank you for your answers!

handle clickevent in appbar in fragments android studio

I am facing a problem with my custom appbar in my fragment where nothing happens when I click any item in my appbar. I have followed this document to create an appbar in my fragment but still so success.
I have one activity that contains only a fragment container which I switch between fragments from. In one of fragments I want to add a custom fragment owned appbar. I first created a menu like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/settings"
android:title="Settings"
android:icon="#drawable/ic_settings"
app:showAsAction="never">
</item>
<item
android:id="#+id/about"
android:title="About"
android:icon="#drawable/ic_about"
app:showAsAction="never">
</item>
<item
android:id="#+id/logout"
android:title="Logout"
android:icon="#drawable/ic_logout"
app:showAsAction="never">
</item>
</menu>
then in my profile.xml I added a toolbar like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainFragments.AddFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/Bar_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/darkBlue"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed">
//alot of code in between....
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_prof"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
//more stuff implemented
</RelativeLayout>
however, my menu does not get inflated and if i inflate it via xml nothing happens when I click on any item, what is wrong? Thanks!
here is how my profile fragment looks like:
Edit
here is full profilefragment.java:
package se.umu.moad0012.myservice.MainFragments;
import se.umu.moad0012.myservice.Adapters.FragmentPagerAdapter;
import se.umu.moad0012.myservice.MainActivity;
import se.umu.moad0012.myservice.Models.User;
import se.umu.moad0012.myservice.ProfileFragments.AboutFragment;
import se.umu.moad0012.myservice.ProfileFragments.SettingsFragment;
import se.umu.moad0012.myservice.R;
import se.umu.moad0012.myservice.StartFragments.LoginFragment;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.makeramen.roundedimageview.RoundedImageView;
public class ProfileFragment extends Fragment {
private RoundedImageView mProfileRoundedImageView;
private TextView mPosts, mFollowers, mFollowing, mUserName;
private TabLayout mTabLayout;
private String profileId;
private FirebaseDatabase mFirebaseDatabase;
private ViewPager2 mViewPager2;
private final String[] titles = new String[]{"Posts", "Reviews"};
private final int[] icons = new int[]{R.drawable.ic_grid, R.drawable.feedback};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
//declare variables
declareVariables(v);
//adapter for viewpager2
mViewPager2.setAdapter(new FragmentPagerAdapter(this));
//configure tabs here
tabMediator();
//FirebaseAuth.getInstance().signOut();
//set profile info
setProfileInfo();
return v;
}
private void tabMediator() {
new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText(titles[position]);
tab.setIcon(icons[position]);
}
}).attach();
}
private void setProfileInfo() {
mFirebaseDatabase.getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUserName.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void declareVariables(View v) {
mViewPager2 = v.findViewById(R.id.viewpager_profile);
mTabLayout = v.findViewById(R.id.tabLayout_profile);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserName = v.findViewById(R.id.userNameProfileFragment);
mFollowers = v.findViewById(R.id.followers);
mPosts = v.findViewById(R.id.posts);
mFollowing = v.findViewById(R.id.following);
//mProfileRoundedImageView = v.findViewById(R.id.profileImage);
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
profileId = fUser.getUid();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar_prof);
toolbar.inflateMenu(R.menu.popup_menu_profile);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.settings:
Log.d("TAG", "onOptionsItemSelected: settings");
return true;
case R.id.about:
Log.d("TAG", "onOptionsItemSelected: about");
return true;
case R.id.logout:
Log.d("TAG", "onOptionsItemSelected: logout");
return true;
}
return false;
}
});
}
}
Edit2
I have noticed just now that it works, just that my text is white and thus does not show up. Sorry for any inconvenience.
Put this in your fragment
public class ProfileFragment extends Fragment {
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = view.findViewById(R.id.my_toolbar);
toolbar.inflateMenu(R.menu.your_menu);
toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//handle click
return true;
case R.id.new_pic:
// handle here
return true;
default:
return false;
}
}
});
}
}

Getting raw data when attempting to retrieve Edittext input with a view model

I am trying to build a multi page form for an application. As per suggestions here I am attempting to use a ViewModel to store the data input by the user to easily get it in another fragment, and to update the edittext to their previous input if they navigate back and forth. As well the application must have view binding.
However, when attempting to retrieve the input in a toast message in the last fragment or put it in the edittext, I get this as an output
"androidx.lifecycle.MutableLiveData#8177d2c"
Why is this happening? I am using .toString() methods with getText() so I don't know why
My code:
SharedViewModel.java
package com.loopbreakr.viewmodelform;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.MutableLiveData;
public class SharedViewModel extends ViewModel {
private MutableLiveData<CharSequence> answerOneText = new MutableLiveData<>();
private MutableLiveData<CharSequence> answerTwoText = new MutableLiveData<>();
private MutableLiveData<CharSequence> answerThreeText = new MutableLiveData<>();
public void setAnswerOneText(CharSequence input) {
answerOneText.setValue(input);
}
public void setAnswerTwoText(CharSequence input) {
answerTwoText.setValue(input);
}
public void setAnswerThreeText(CharSequence input){
answerThreeText.setValue(input);
}
public MutableLiveData<CharSequence> getAnswerOneText() {
return answerOneText;
}
public MutableLiveData<CharSequence> getAnswerTwoText() {
return answerTwoText;
}
public MutableLiveData<CharSequence> getAnswerThreeText() {
return answerThreeText;
}
}
MainActivity.java
package com.loopbreakr.viewmodelform;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();
}
}
PageOne.java fragment that I am trying to retrieve data from
package com.loopbreakr.viewmodelform;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.loopbreakr.viewmodelform.databinding.FragmentPageOneBinding;
public class PageOne extends Fragment {
private SharedViewModel sharedViewModel;
private FragmentPageOneBinding binding = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewDataBinding fragmentBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_page_one,container,false);
binding = (FragmentPageOneBinding) fragmentBinding;
return binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
if(binding != null){
binding.pageOneInput.setText(sharedViewModel.getAnswerOneText().toString());
binding.nextToTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedViewModel.setAnswerOneText(binding.pageOneInput.getText().toString());
goNext();
}
});
binding.returnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
}
}
public void goNext() {
NavController navController = Navigation.findNavController(getView());
navController.navigate(R.id.action_pageOne_to_pageTwo);
}
public void goBack(){
NavController navController = Navigation.findNavController(getView());
navController.navigate((R.id.action_pageOne_to_description));
}
}
Last fragment PageThree.java where I attempt to get the data and display it as a toast message
package com.loopbreakr.viewmodelform;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.loopbreakr.viewmodelform.databinding.FragmentPageOneBinding;
public class PageOne extends Fragment {
private SharedViewModel sharedViewModel;
private FragmentPageOneBinding binding = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewDataBinding fragmentBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_page_one,container,false);
binding = (FragmentPageOneBinding) fragmentBinding;
return binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
if(binding != null){
binding.pageOneInput.setText(sharedViewModel.getAnswerOneText().toString());
binding.nextToTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedViewModel.setAnswerOneText(binding.pageOneInput.getText().toString());
goNext();
}
});
binding.returnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
}
}
public void goNext() {
NavController navController = Navigation.findNavController(getView());
navController.navigate(R.id.action_pageOne_to_pageTwo);
}
public void goBack(){
NavController navController = Navigation.findNavController(getView());
navController.navigate((R.id.action_pageOne_to_description));
}
}
Also, here are the XMLs incase they are relevant
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_page_one.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.loopbreakr.viewmodelform.SharedViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PageOne">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/nextToTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="#+id/returnButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Return"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<MultiAutoCompleteTextView
android:id="#+id/pageOneInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textAutoCorrect|textMultiLine"
android:maxLines="4"
android:minLines="4"
app:layout_constraintBottom_toBottomOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
override the toString method in model class it will work
#Override
public String toString() {
return "BeanDetails{" +
"sl_no='" + sl_no + '\'' +
", type='" + type + '\'' +
", count='" + count + '\'' +
", percent='" + percent + '\'' +
'}';
}
in my model class there is four variable so that is why it is showing 4 variable inside the beandetails

Android Fragment not showing in app

So I'm creating an app and I'm stuck with this problem of my fragment not showing on screen. It looks just fine on Android Studio preview, but when run on real device I only see action bar and nothing else.
Here's my fragment code:
<?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:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/fragment_login_userEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/>
<EditText
android:id="#+id/fragment_login_userPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_login_loginButton"
android:text="Sign In"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_login_registerButton"
android:text="Sign Up"/>
</LinearLayout>
LoginFragment code:
package com.dario.beastchat.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.dario.beastchat.R;
import com.dario.beastchat.R2;
import com.dario.beastchat.activities.BaseFragmentActivity;
import com.dario.beastchat.activities.RegisterActivity;
import com.dario.beastchat.utils.Constants;
import java.net.URISyntaxException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.socket.client.IO;
import io.socket.client.Socket;
public class LoginFragment extends BaseFragment {
#BindView(R2.id.fragment_login_userEmail)
EditText mUserEmailEt;
#BindView(R2.id.fragment_login_userPassword)
EditText mUserPasswordEt;
#BindView(R2.id.fragment_login_loginButton)
Button mLoginButton;
#BindView(R2.id.fragment_login_registerButton)
Button mRegisterButton;
private Unbinder mUnbinder;
private Socket mSocket;
public static LoginFragment newInstance(){
return new LoginFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSocket = IO.socket(Constants.IP_LOCAL_HOST);
} catch (URISyntaxException e) {
Log.i(LoginFragment.class.getSimpleName(), e.getMessage());
Toast.makeText(getActivity(), "Cant connect to the server", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mSocket.connect();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
mUnbinder = ButterKnife.bind(this, rootView);
return rootView;
}
#OnClick(R2.id.fragment_login_registerButton)
public void setmRegisterButton(){
startActivity(new Intent(getActivity(), RegisterActivity.class));
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
}
}
BaseFragment class:
package com.dario.beastchat.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And BaseFragment activity:
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.dario.beastchat.R;
public abstract class BaseFragmentActivity extends AppCompatActivity {
abstract Fragment createFragment();
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_fragment_base);
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_fragment_base_fragmentContainer);
if (fragment ==null) {
fragment = createFragment();
fragmentManager.beginTransaction()
.add(R.id.activity_fragment_base_fragmentContainer, fragment)
.commit();
}
}
}
What am I doing wrong?
if (fragment ==null) {
fragment = createFragment();
fragmentManager.beginTransaction()
.add(R.id.activity_fragment_base_fragmentContainer, fragment)
.commit();
}
Problems is .add
try to replace it to replace

Error while using ListFragement

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Categories

Resources