Я пытаюсь внедрить прослушиватель WifiScanner в свой ScanFragment, но я получаю эту ошибку: java.lang.ClassCastException: emilsoft.wifitest3.MainActivity cannot be cast to emilsoft.wifitest3.WifiScanner$Listener
Я уже делал это с обычной деятельностью, и теперь я пытаюсь преобразовать ее в Фрагменты, о которых я сейчас их узнаю. Я провел много исследований, но не нашел рабочего решения. Я заметил код, в котором есть ошибкаClassCastException: MainActivity не может быть передан слушателю
Так что мой Основная деятельность:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
Мой SectionsPagerAdapter класс:
public class SectionsPagerAdapter extends FragmentPagerAdapter{
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: return ScanFragment.newInstance();
}
return null;
}
Мой ScanFragment:
public class ScanFragment extends Fragment implements WifiScanner.Listener {
private ScanCollector sc;
private WifiManager wifi;
public ScanFragment() {}
public static ScanFragment newInstance() {
return new ScanFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_scan_results, container, false);
wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
sc = new ScanCollector(this.getContext()); //THE ERROR STARTS HERE
return result;
}
Мой ScanCollector класс (которые обрабатывают слушатели добавляют к классу WifiScanner):
public class ScanCollector {
// The context wrapper that we'll use for accessing system services, receiving
// broadcasts from the WifiManager
private final Context context;
private WifiScanner.Listener listener;
public ScanCollector(Context context) {
if (context == null)
throw new NullPointerException();
this.context = context;
this.listener = (WifiScanner.Listener)context; //THE ERROR IS HERE
}
Проблема заключается в том, что я не могу передать правильный контекст в мой класс ScanCollector, который затем бросил его к WifiScanner.Listener. Наверное, это очень глупое решение, но я не могу его найти.
Заранее благодарен!
Это сработало спасибо! – Automatik
@Pelocho Рабочий человек !! Спасибо –