Reputation: 362
I need help , for onclick on recyclerview and open new fragment activity, im clicked in item list close app and logcat error is: Unable to instantiate activity ComponentInfo{com.example.divemex/com.example.works.Pem}: java.lang.ClassCastException: com.example.works.Pem cannot be cast to android.app.Activity
My code adapter:
@Override
public void onBindViewHolder(final tramoView tramoView, final int i) {
final TramoModel tramoModel = tramoList.get(i);
tramoView.txtnombreMostrar.setText(tramoModel.getTramoName());
tramoView.txtnombreMostrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Pem.class);
v.getContext().startActivity(intent);
} });
}
My code class fragment:
public class Pem extends Fragment {
private TabAdapter adapter;
private TabLayout tableLayout;
private ViewPager viewPager;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tabs, container, false);
viewPager = view.findViewById(R.id.request_orders_view_pager);
tableLayout = view.findViewById(R.id.request_orders_tabs);
adapter = new TabAdapter(getFragmentManager());
// adapter = new TabAdapter(FragmentActivity.getSupportFragmentManager());
adapter.addFragment(new fragment1(), "Tab 1");
adapter.addFragment(new fragment2(), "Tab 2");
adapter.addFragment(new fragment3(), "Tab 3");
adapter.addFragment(new fragment4(), "Tab 4");
viewPager.setAdapter(adapter);
tableLayout.setupWithViewPager(viewPager);
return view;
}
}
Error :
Upvotes: 1
Views: 680
Reputation: 40830
You are trying to deal with fragments like activities. One of Intents
purpose is to start new activities, but not fragments.
You got an exception in below line of code, because you use an Intent
to start a Fragment
(as Pem.class
is a fragment); and fragments can't start this way.
Intent intent = new Intent(v.getContext(), Pem.class);
And this is obvious in the Exception you got java.lang.ClassCastException: com.example.works.Pem cannot be cast to android.app.Activity
Which indicates that it's not allowed to cast Pem.class to an Activity; that is because it doesn't extend Activity
class or any of its sub-classes.
To solve this, either:
AppCompatActivity
class
(or any activity class), and replace the activity's callback methods
instead of the fragment ones.Upvotes: 1
Reputation: 209
You use this : Intent intent = new Intent(v.getContext(), Pem.class); v.getContext().startActivity(intent);
But Pem
is a Fragment
, not an Activity
.
Upvotes: 0