Reputation: 368
In fragment ---my RecyclerViewAdapter On click
ImageRecycleAdapter.OnImageClicklistener onImageClicklistener=new ImageRecycleAdapter.OnImageClicklistener() {
@Override
public void onItemClicks(View view, int position) {
Log.e("onitemclic image",""+position);
OnimageUrlPass onimageUrlPass=(OnimageUrlPass)getContext();
onimageUrlPass.getUrllist(image_final);
Intent intent=new Intent(getContext(),ImagePagerAct.class);
startActivity(intent);
}
};
Interface in fragment
public interface OnimageUrlPass{
void getUrllist(ArrayList<ImageUrl> url);
}
In Activity Implements
public class ImagePagerAct extends AppCompatActivity implements ImageFag.OnimageUrlPass{}
In Activity Implements method
@Override
public void getUrllist(ArrayList<ImageUrl> url) {
this.imageUrl=url;
}
error
java.lang.ClassCastException: com.example.user.newsweats.UI.MainAct cannot be cast to com.example.user.newsweats.frag.ImageFag$OnimageUrlPass
Upvotes: 1
Views: 1472
Reputation: 736
There are two different ways to send data from activity to fragment. Pass data as the argument when you create using the factory method.
public static SimpleFragment getInstance(Bundle bundle) {
SimpleFragment simpleFragment = new SimpleFragment();
simpleFragment.setArguments(bundle)
return simpleFragment;
}
Through this method you can pass simple objects like string.
Still, you can pass some complex objects by converting that object into parseable.
new Bundle().putParcelable("Key", ParcebleObject);
Using interface, you can pass almost any data. Create an interface, in my case I create an interface called SomeEventListener.
Interface
public interface SomeEventListener {
public onSomeEventHappened(ArrayList<String> arrayListOfString);
}
Fragment class
public class SimpleFragment extends Fragment implement SomeEventHappened {
public interface onSomeEventListener {
private ArrayList<String> arrayList;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, null);
//..........
return v;
}
public onSomeEventHappened(ArrayList<String> arrayListOfString) {
this.arrayList = arrayListOfString;
}
}
In your MainActivity.java file
public class MainActivity extends AppCompatActivity {
@override
public void onCreate(Bundle savedInstanceState) {
//........
ArrayList<String> array = new ArrayList<>();
SimpleFragment fragment = new SimpleFragment();
SomeEventListener listener = fragment.getEventListener();
listener.onSomeEventHappened(array);
}
This will work for any kind of object.
Upvotes: 3
Reputation: 2446
It seems you put wrong Context
object to your RecyclerViewAdapter
constructor. Thats why object returned by getContext
never could be cast to OnimageUrlPass
interface. Try to call adapter constructor inside ImagePagerAct
with new RecyclerViewAdapter(this)
.
Upvotes: 2