Android Fragment Type Mismatch - java

I am new to android and am following the tutorial at Dartmouth. http://www.cs.dartmouth.edu/~campbell/cs65/lecture08/lecture08.html
I am following all the codes and at the MainActivity.java,
// create the fragments
Fragment mFindFragment = new FindFragment();
Fragment mChatFragment = new ChatFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
mChatTab.setTabListener(new MyTabsListener(mChatFragment,
getApplicationContext()));
I have encountered this error: Type mismatch: cannot convert from FindFragment to Fragment. So I follow the fix error suggestions and change the code to
// create the fragments
FindFragment mFindFragment = new FindFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
Now, there is a new error: The constructor MyTabsListener(FindFragment, Context) is undefined.
Just in case the imports are critical, here they are:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
For myTabsListener:
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public MyTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
}
For my FindFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FindFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.findfragment, container, false);
}
}
I am pretty confused here. I am not sure if this is related to my import, lib setup or other problems. Thanks in advance!

You need to change this
import android.support.v4.app.Fragment;
// you will use this import when you want fragment from support library
// in that case you will extend FragmentActivity which is the base class for support based fragments
to
import android.app.Fragment;
in FindFragment.java.
Similarly do the same in ChatFragment.java also

Related

how to add a fragment to the navigation drawer menu item fragment

I have a store item fragment in the navigation drawer item menu in this fragment I will like to known how to add another fragment to it if the user click on the Imageview icon then still maintain my navigation drawer below is my try
package com.example.entertainmentlab.ui.store;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.entertainmentlab.R;
import com.example.entertainmentlab.ui.setting.SettingViewModel;
public class StoreFragment extends Fragment {
private StoreViewModel StoreViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
StoreViewModel =
ViewModelProviders.of(this).get(StoreViewModel.class);
View root = inflater.inflate(R.layout.fragment_store, container, false);
final ImageView MusicButton = root.findViewById(R.id.music_btn);
//I want to move to the next Fragment if the user click the music icon
MusicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Fragment fragment = new BlankFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_store, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}catch (Exception e ){
Toast.makeText(getActivity(), "erro "+e, Toast.LENGTH_SHORT).show();
}
}
});
// StoreViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
// #Override
// public void onChanged(#Nullable String s) {
// textView.setText(s);
// }
// });
return root;
}
}
if the user click the image icon I want to send he/she to the music fragment and then still maintaining the drawer and allow him to return back to the previous fragment
i suggest to you use a AlertDialog for do this work but you can make full screen AlertDialog...

How to call dialogfragment from another fragment?

I'm really new in android development, hope you guys can help me in my problem. I had already search for any solution but none of it works.
I have 6 fragments for scrollable tabs, then each tabs has ADD TO CART buttons, if I click that button a fragment dialog should appear. In my case, there is this error.
Error:(37, 13) error: no suitable method found for show(android.support.v4.app.FragmentManager,String)
method DialogFragment.show(android.app.FragmentManager,String) is not applicable
(argument mismatch; android.support.v4.app.FragmentManager cannot be converted to android.app.FragmentManager)
method DialogFragment.show(FragmentTransaction,String) is not applicable
(argument mismatch; android.support.v4.app.FragmentManager cannot be converted to FragmentTransaction)
Heres my code by the way for the fragment to call the DialogFragment.
package info.androidhive.materialtabs.fragments;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import info.androidhive.materialtabs.R;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
public void toDiagCartFragment(View v){
FragmentManager manager = getFragmentManager();
CartFragment cart = new CartFragment();
cart.show(manager, "My Cart");
}
}
This the code for DialogFragment to be called by OneFragment
package info.androidhive.materialtabs.fragments;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import info.androidhive.materialtabs.R;
public class CartFragment extends DialogFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cart2, null);
}
}
Seems like the error is in the OneFragment.java
Heres my output by the way.
_I really appreciate for any answers, just please be nice to me
.I really don't know how to do it . :(
.Thanks :)
your error says your answer clearly.
type mismatch
your dialogFragment has android.app.FragmentManager and you are calling android.support.v4.app.FragmentManager. you should use getSupportFragmentManger() insted of getFragmentManager();
first of all replace your cartFragment import to this,
import android.support.v4.app.DialogFragment;
and create this method.
public static CartFragment newInstance() {
CartFragment dialog = new CartFragment ();
return dialog;
}
and in your one_fragment use like this.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
CartFragment newFragment = CartFragment .newInstance();
newFragment.show(ft, "My Cart");
your OneFragment belongs to support library fragment while CartFragment doesn't. you need to either modify CartFragment to support library or OneFragment to default Fragment. and modifying CartFragment to support library fragment will be better as support library has more functionality.
There is a version mismatch. Instead of using getFragmentManager(), use getSupportFragmentManager() as you are using the support library version of Fragments.
Replace
FragmentManager manager = getFragmentManager();
with
FragmentManager manager = getSupportFragmentManager();

Android - Wrong 1st argument type and ' android.supportv4.app.Fragment'

I'm creating a Material design tab view. I'm getting an error after addFragment method on my Main Activity. This is the error that I'm getting.
Wrong 1st argument type. Found: 'com.example.sa.tabproject.LatestPromoFragment, ' android.supportv4.app.Fragment'
My MainActivity.java
import android.app.Activity;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.app.Fragment;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout=(TabLayout)findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter= new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new LatestPromoFragment(),"Latest Promos"); // new LatestPromoFragment() should be in getItem() otherwise it will cause crashes
viewPagerAdapter.addFragment(new MapViewFragment(),"Map View"); // new MapViewFragment() should be in getItem() otherwise it will cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}}
ViewPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragment = new ArrayList<>(); // this line can cause crashes
ArrayList<String> tabTitles= new ArrayList<>();
public void addFragment(Fragment fragment,String titles){
this.fragment.add(fragment); // this line can cause crashes
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragment.get(position); // this should create the Fragment instances
}
#Override
public int getCount() {
return fragment.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}}
I imported several fragment classes to the MainActivity.java. But it doesn't fix the error.
This is because in adapter class you are using support fragment i.e import android.support.v4.app.Fragment; and in Activity class you are using app fragment import android.app.Fragment;
use same type of fragment every where it will work.
If you use android.support.v4.app.FragmentPagerAdapter, you must also use android.support.v4.app.Fragment for all Fragments.
If you want to use android.app.Fragment native Fragments with a FragmentPagerAdapter or FragmentStatePagerAdapter, you need to use the v13 support library versions of the adapter, i.e. android.support.v13.app.FragmentPagerAdapter.
You can see this in the documentation if you look at the getItem() for each:
V4:
http://developer.android.com/intl/en/reference/android/support/v4/app/FragmentPagerAdapter.html#getItem(int)
V13:
http://developer.android.com/intl/en/reference/android/support/v13/app/FragmentPagerAdapter.html#getItem(int)
Replace your import android.app.Fragment; code
with
import android.support.v4.app.Fragment;

Constructor within activity is undefined

I have been fighting with this error for a couple of hours and I am not able to continue. I need your help here!
I am trying to replace my previous TabNavigation at ActionBar by a ViewPager in SDK21, looking at comments within StackOverflow I found this webpage, where the use of PagerTabStrip is described with an example, so I tried to implement it in my activity, however I am getting an strange error.
I tried to google the problem and all the suggestions are not really applicable to my problem (wrong parameters in the constructor are the usual errors) . I also reproduced the error with a simple Activity in order to avoid anything I have in my previous activity, but the error keeps. I attach you here the code I replicated isolated:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestActivity extends Activity {
CustomPagerAdapter mCustomPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adding_users_to_list);
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
}
class CustomPagerAdapter extends FragmentPagerAdapter {
Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// Create fragment object
Fragment fragment = new DemoFragment();
// Attach some data to the fragment
// that we'll use to populate our fragment layouts
Bundle args = new Bundle();
args.putInt("page_position", position + 1);
// Set the arguments on the fragment
// that will be fetched in the
// DemoFragment#onCreateView
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + (position + 1);
}
}
class DemoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource that'll be returned
View rootView = inflater.inflate(R.layout.fragment_users, container, false);
// Get the arguments that was supplied when
// the fragment was instantiated in the
// CustomPagerAdapter
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text_option)).setText("Page " + args.getInt("page_position"));
return rootView;
}
}
}
I am getting in the call to the constructor the following error:
"The constructor TestActivity.CustomePageAdapter(FragmentManager, Context) is undefined"
In here:
mCustomPagerAdapter = new CustomPagerAdapter(getFragmentManager(), this.getApplicationContext());
I have tried to introduce the Adapter outside and inside the activity definition and is still not working. Is likely to be something simple, but... I can't see it and I need other eyes. Any idea what I am doing wrong?
change the import of the activity to:
import android.support.v4.app.FragmentActivity;
Also change constructor to:
mCustomPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), this.getApplicationContext());
The reason is that your activity is used from the ADT:
import android.app.Activity;
and the Fragments used from the support package:
import android.support.v4.app.FragmentManager;
change the import of the activity to:
import android.support.v4.app.FragmentActivity;

How do pass a ActionBarAcivity as an Intent?

I tried to have a view of an ActionBarActivity opening after hitting a spinner button.
There are two items on my spinner, the second one runs fine, but when I tried to access the Categorias item the app throws me a NullPointerException inside the DrawerActivity class. I don't actually know where the problem is. Another ActionBarActivity extension class that I have runs perfectly.
I'm new to Android/Java development.
The Spinner Fragment
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerFragment extends Fragment {
private static Spinner spinner;
private int selected;
private View mView;
static void setSpinnerContent( View view ){
spinner = (Spinner) view.findViewById(R.id.spinner1);
return ;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_spinner, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
/**
* Maneja las acciones seleccionadas del Spinner
*/
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
selected = spinner.getSelectedItemPosition();
switch(selected){
case 1:
Intent categorias = new Intent( );
categorias.setClass( getActivity() , NavigationDrawerActivity.class );
startActivity(categorias);
break;
case 2:
Intent convenios = new Intent();
convenios.setClass(getActivity(), ConveniosFragment.class);
startActivity(convenios);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return view;
}
}
The Navigation Drawer Activity extends a ActionBarActivity
package inmostla.ligatangamanga.pruebaintegrar.navigationdrawer;
import inmostla.ligatangamanga.pruebaintegrar.navigationdrawer.NavigationDrawerFragment;
import inmostla.ligatangamanga.pruebaintegrar.R;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class NavigationDrawerActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}...
Maybe that's because getActivity() returns null. Try overriding onAttach() and keep Activity reference as a field in your class. Use this reference instead of getActivity() when you needed a reference to context or activity.

Categories