RecyclerView and Item Position and click on particular item - android-recyclerview

This is the interface of my application, my question is, if I click on "video lecture" then it should go to Video Lecture Activity and if i click on "Detail Notes" then it should go in Detail Notes Activity. Similarly, i want to do with all recyclerView items.
This is my Adapter code
package com.example.motionofknowledge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.motionofknowledge.databinding.ActivityMaterialsBinding;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class Materials extends AppCompatActivity {
ActivityMaterialsBinding binding;
FirebaseFirestore database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMaterialsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
String head = getIntent().getStringExtra("subName");
TextView textView = findViewById(R.id.headingMat);
textView.setText(new String(head));
database = FirebaseFirestore.getInstance();
ArrayList<MatModel> materials = new ArrayList<>();
MatAdapter adapter = new MatAdapter(this,materials);
String subId = getIntent().getStringExtra("subId");
database.collection("subjects")
.document(subId)
.collection("mat")
.orderBy("index")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
materials.clear();
for (DocumentSnapshot snapshot:value.getDocuments()){
MatModel model = snapshot.toObject(MatModel.class);
model.setMatId(snapshot.getId());
materials.add(model);
}
adapter.notifyDataSetChanged();
}
});
binding.matList.setLayoutManager(new GridLayoutManager(this,2));
binding.matList.setAdapter(adapter);
binding.matHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Materials.this,MainActivity.class);
startActivity(intent);
}
});
}
}
This is my adapter code
package com.example.motionofknowledge;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MatAdapter extends RecyclerView.Adapter<MatAdapter.MatViewHolder>{
Context context;
ArrayList<MatModel> matModels;
public MatAdapter(Context context, ArrayList<MatModel> matModels){
this.context = context;
this.matModels = matModels;
}
#NonNull
#Override
public MatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_category,null);
return new MatViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MatViewHolder holder, int position) {
MatModel model = matModels.get(position);
holder.textView.setText(model.getMatName());
Glide.with(context)
.load(model.getMatImage())
.into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,Chapters.class);
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return matModels.size();
}
public class MatViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public MatViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.category);
}
}
}

You did not post your adapter code, but your activity code. Anyway: I understand that you have a recyclerView with different kind of items in it (Video Lecture, Detail Notes, and more). Depending on which item the user clicks, you want to do different things.
This is done by using the onBindViewHolder method in your MatAdapter. This method does not only bind the data to the UI layout, but it should also be used to bind a click listener to the UI layout.
If you have only a few items in your RecyclerView, you could use the getItem(position) method of your adapter to find out what specific item you are dealing with within onBindViewHolder. As soon as you know what kind of item the Adapter wants to bind, you can set the according click listener.
See this suggestion:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = null
if (model.type == VIDEO) {
intent = new Intent(context,Video.class);
} else if (model.type == DETAILS) {
intent = new Intent(context,Details.class);
} else {
...
}
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
model is the current MatModel that you want to bind.
model.type is any way to distinguish the different items. I do not know the details of the MatModel class, but you somehow need to be able to distinguish the different models, of course.

Related

How is it possible to reach a checkbox or something else object from an other class

I have a list application what uses Recyclerview. All line have an checkbox, 2pcs TextView and a button. These are declarated in the RecyclerView class.
The application has got an other class what handles the data for example SharedPreferences, and calculations and so on...
How is it possible that I reach the objects what are in RecyclerView from the other class.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public TextView myTextView, subtext;
public Button add;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
myTextView.setText(meta_data);
subtext.setText(meta_subdata +" "+ meta_subdata2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done =itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
and Here is the list class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
adapter.done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.done.isChecked()) Toast.makeText(ToDoList.this,"Something is done",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(View view, int position) {
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
String item_click =adapter.getItem(position);
String[] itemarray = item_click.split(" ",0);
myEdit = sharedPreferences.edit();
myEdit.remove(itemarray[0]);
myEdit.commit();
adapter.notifyItemRemoved(position);
items.remove(item_click);
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
The first attemption was that the objects were declarated in the ViewHolder class, but I can not reach that from the list class.
I put the objects to the RecyclerView class and now I can reach thoose because for example the adapter.done.setOnClickListener() is valid from Android Studio point of view, but I always got null object reference. I think I know why, because the layout xml what the list class uses haven't got checkbox item, but then I don't know how can I solve this.
I also try to inflate the RecyclerView layout:
final View view = mInflater.inflate(R.layout.recyclerview_row,null);
...
...
...
adapter.done = view.findViewById(R.id.done);
but then I got LayoutInflater null object reference exception.

I have got this error (Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference)

I am trying to display the API data in the recyclerView but facing
this error In the viewHolder.I'm trying to set the text of the textviews from the fetched data on my API, but when i try to do so, it
throws the following error (Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference)
package com.example.restfulapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DataViewActivity extends AppCompatActivity {
RecyclerView recyclerView;
private static final String TAG = "DataViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_view);
recyclerView = findViewById(R.id.recycle);
listingData();
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL, false );
recyclerView.setLayoutManager(llm);
}
private void listingData() {
Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
Call<Model> listingData = methods.getAllData();
listingData.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (response.isSuccessful()) {
recycleAdapter adapter =new recycleAdapter(response.body().getData());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(DataViewActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}
class recycleAdapter extends RecyclerView.Adapter<recycleAdapter.MyViewHolder>
{
List<Model.data> list;
public recycleAdapter(List<Model.data> list) {
this.list = list;
}
#NonNull
#Override
public recycleAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users,null);
recycleAdapter.MyViewHolder viewHolder = new recycleAdapter.MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull recycleAdapter.MyViewHolder holder, int position) {
holder.userEmail.setText(list.get(position).getEmail());
holder.firstName.setText(list.get(position).getFirst_name());
holder.lastName.setText(list.get(position).getLast_name());
Picasso.with(getApplicationContext()).load(list.get(position).getAvatar())
.placeholder(R.drawable.ic_launcher_background).fit().into(holder.userImage);
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView firstName,lastName,userEmail;
ImageView userImage;
There is an error on this section below, I have mentioned the error
above.Am I missing something or did I do something wrong in my code?
public MyViewHolder(#NonNull View itemView) {
super(itemView);
firstName =(TextView) findViewById(R.id.firstName);
lastName = (TextView) findViewById(R.id.lastName);
userEmail = (TextView) findViewById(R.id.userEmail);
userImage = (ImageView) findViewById(R.id.userImage);
}
}
}
}

How can i display the message from receiver in an chat application in android studio?

We have programmed a chat application with Firebase in which the sender's messages are to be displayed on the right and those of the recipient on the left side.
The sender's messages are correctly displayed on the right side if you send the message with the Send button.
Unfortunately, the messages to the receiver are not shown on the left side.
Our Recyclerview java Code is this one:
package com.example.myapplicationsonet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Message_recyclerview extends AppCompatActivity {
TextView tvUsername;
ImageButton ibtnSend;
EditText etMessage;
FirebaseUser fuser;
DatabaseReference databaseReference;
MessageAdapter messageAdapter;
List<message_helperclass> mChat;
RecyclerView recyclerView;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_message_recyclerview );
recyclerView = (RecyclerView) findViewById(R.id.rvmessage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
tvUsername = (TextView) findViewById(R.id.textView_message_username);
etMessage = (EditText) findViewById(R.id.messagebox);
ibtnSend = (ImageButton) findViewById(R.id.button_send);
intent = getIntent();
final String username = intent.getStringExtra("username");
fuser = FirebaseAuth.getInstance().getCurrentUser();
fuser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(username);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
tvUsername.setText(username);
readMessages(fuser.getUid(), username);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ibtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMessage.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), username, msg);
}else {
Toast.makeText(Message_recyclerview.this, "Du kannst keine leeren Nachrichten versenden", Toast.LENGTH_LONG).show();
}
etMessage.setText("");
}
});
}
private void sendMessage(String sender, String receiver, String message ){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
databaseReference.child("Chats").push().setValue(hashMap);
}
private void readMessages(final String myid, final String username){
mChat = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
message_helperclass chat = snapshot.getValue(message_helperclass.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(username) ||
chat.getReceiver().equals(username) && chat.getSender().equals(myid)){
mChat.add(chat);
}
messageAdapter = new MessageAdapter(Message_recyclerview.this, mChat);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And this is our Adapter Class:
package com.example.myapplicationsonet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<message_helperclass> mChat;
FirebaseUser fUser;
public MessageAdapter(Context mContext, List<message_helperclass> mChat){
this.mChat = mChat;
this.mContext = mContext;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
message_helperclass chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
}
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fUser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
Unfortunately, we cannot find the error why the recipient messages are not displayed on the left.
I hope you can help us. It would be important.
Thanks!
Can't Comment, but have you checked your chat_item_right and chat_item_left XML file? Your code appears right so the error might be there.

save cardview in sharedpreferences

I have a recyclerview with card view. I want to change the image of one of them after click on it (It will go to another activity) but when I come back or after closing and reopening the app I don't want to change the image . I know that I should use Shared preferences but I'm totally confused and I don't know what should I do.
This is my custom recyclerview:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.PriorityQueue;
import static android.content.Context.MODE_PRIVATE;
public class LessonRecViewAdapter extends RecyclerView.Adapter<LessonRecViewAdapter.ViewHolder> {
private static final String TAG = "LessonRecViewAdapter";
private ArrayList<Lesson> lessons = new ArrayList<>();
private ViewHolder holder;
private Context context;
public LessonRecViewAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_lesson_rec_view, parent, false);
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called");
holder.txtLessons.setText(lessons.get(position).getLessonNumber());
final int imgSad = R.mipmap.sad;
final int imgSmile = R.mipmap.smile;
final int imgPlain = R.mipmap.plain;
Glide.with(context)
.asBitmap()
.load(imgPlain)
.into(holder.imageView);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int lessonId = lessons.get(position).getLessonId();
switch (lessons.get(position).getLessonId()) {
case 1:
Intent intent = new Intent(context, Lesson1Activity.class);
context.startActivity(intent);
break;
case 2:
Toast.makeText(context, "Comming Soon", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
}
#Override
public int getItemCount() {
return lessons.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView imageView;
private TextView txtLessons;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.card_view);
imageView = itemView.findViewById(R.id.image_view);
txtLessons = itemView.findViewById(R.id.txt_lessons);
}
}
public void setWords(ArrayList<Lesson> lessons) {
this.lessons = lessons;
notifyDataSetChanged();
}
}

NullPointerException on FragmentActivity.onBackPressed()

I have a problem on up back icon toolbar, when i click twice to go back app crash on nullpointer exception recalling the error on my getActivity().onBackPressed();
this is the fragment:
package com.example.android.evilsecretgallery;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
public class ImageDetailFragment extends Fragment {
private static final String EXTRA_IMAGE = "image_item";
private static final String EXTRA_TRANSITION_NAME = "transition_name";
public ImageDetailFragment() {
// Required empty public constructor
}
public static ImageDetailFragment newInstance(ImageModel image, String transitionName) {
ImageDetailFragment fragment = new ImageDetailFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_IMAGE, image);
args.putString(EXTRA_TRANSITION_NAME, transitionName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postponeEnterTransition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(getActivity(), R.style.EvilTextAppearance);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageModel image = getArguments().getParcelable(EXTRA_IMAGE);
String transitionName = getArguments().getString(EXTRA_TRANSITION_NAME);
final PhotoView imageView = view.findViewById(R.id.detail_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setTransitionName(transitionName);
}
Glide.with(getActivity())
.asBitmap()
.load(image.getUrl())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
startPostponedEnterTransition();
imageView.setImageBitmap(resource);
}
});
}
}
that go back in this activity:
package com.example.android.evilsecretgallery;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class PagesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
then if I go back again to this activity below it gives me the error:
package com.example.android.evilsecretgallery;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView cover;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
cover = findViewById(R.id.cover_id);
cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new intent to open the PagesActivity
Intent intent = new Intent(MainActivity.this, PagesActivity.class);
// Start the new activity
startActivity(intent);
}
});
Button siteButton = findViewById(R.id.site_button);
siteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://www.evilsecret.it";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
I have made some experiment and if i go back from pages activity it has no problem. I have to use different method in the fragment?
try clean and rebuild your project
It worked for me.