Issue
**I use this code to click in mycontext It shows me error . ** how to use intent activity correctly without error
public void onBindViewHolder(@NonNull final MyFotosAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPosts.get(position);{
holder .image_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
// this code error runtime
Intent intent = new Intent(mContext,ProfileActivity.class);
intent.putExtra("profileid", post.getPublisher());
mContext.startActivity(intent);
/// end
}
});
Logcat: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
Solution
it might be better to call your startActivity()
method in your activity as it would be way better than calling it in your adapter.
To achieve this you should create an interface to communicate between your adapter and your activity.
ClickListener interface:
interface ClickListener {
void onClick(YourModel clickedModel,int position);
}
To use the onClick()
method just pass it as a constructor argument in your adapter like how it is done below:
private ClickListener listener;
public Adapter(ClickListener listener) {
this.listener = listener;
}
In your MainActivity instanciate your adapter like the snippet below:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Adapter myAdapter = new Adapter(new ClickListener() {
@Override
public void onClick(YourModel clickedModel, int position) {
Intent intent = new Intent(MainActivity.this,ProfileActivity.class);
intent.putExtra("profileid", post.getPublisher());
MainActivity.this.startActivity(intent);
}
});
}
Feel free to delete the arguments in onClick()
method in the interface if you don't need them
Answered By - saman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.