In #override onBindViewHolder method, I get an error message:
Non-static field 'mWeatherTextView' cannot be referenced from a
static context
I checked for all possible errors but didn't find any, even my code is similar to the solution provided but there is no error showing for the solution provided.
package com.example.android.sunshine;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ForecastAdapter extends
RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> {
private String[] mWeatherData;
public ForecastAdapter(){}
public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder{
public final TextView mWeatherTextView;
public ForecastAdapterViewHolder(View view){
super(view);
mWeatherTextView =(TextView)view.findViewById(R.id.tv_weather_data);
}
}
#Override
public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
Context context = parent.getContext();
int layoutIdForListItem = R.layout.forecast_list_item;
boolean shouldAttachToParentImmediately = false;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutIdForListItem,
parent,shouldAttachToParentImmediately);
return new ForecastAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(ForecastAdapterViewHolder holder, int position)
{
String weatherForThisDay = mWeatherData[position];
ForecastAdapterViewHolder.mWeatherTextView.setText(weatherForThisDay);
_**/* error message says "Non-static field 'mWeatherTextView' cannot be referenced from a static context" */**_
}
#Override
public int getItemCount() {
if(mWeatherData == null) return 0;
return mWeatherData.length;
}
}
In onBindViewHolder, you will always use the holder that has been passed as an argument. So change ForecastAdapterViewHolder to holder in setText line.
package com.example.android.sunshine;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ForecastAdapter extends
RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> {
private String[] mWeatherData;
public ForecastAdapter(){}
public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder{
public final TextView mWeatherTextView;
public ForecastAdapterViewHolder(View view){
super(view);
mWeatherTextView =(TextView)view.findViewById(R.id.tv_weather_data);
}
}
#Override
public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
Context context = parent.getContext();
int layoutIdForListItem = R.layout.forecast_list_item;
boolean shouldAttachToParentImmediately = false;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutIdForListItem,
parent,shouldAttachToParentImmediately);
return new ForecastAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(ForecastAdapterViewHolder holder, int position)
{
String weatherForThisDay = mWeatherData[position];
holder.mWeatherTextView.setText(weatherForThisDay);
_**/* error message says "Non-static field 'mWeatherTextView' cannot be referenced from a static context" */**_
}
#Override
public int getItemCount() {
if(mWeatherData == null) return 0;
return mWeatherData.length;
}
}
Instead of ForecastAdapterViewHolder.mWeatherTextView.setText(weatherForThisDay);
use
holder.mWeatherTextView.setText(weatherForThisDay);
Related
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 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);
}
}
}
}
Error on logcat:
2021-02-18 00:36:44.712 11507-11507/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chitchat, PID: 11507
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.chitchat.RecycleAdapter.onBindViewHolder(RecycleAdapter.java:56)
at com.example.chitchat.RecycleAdapter.onBindViewHolder(RecycleAdapter.java:16)
//////////////////////code from fragment activity////////////////////
package com.example.chitchat;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link homefragrent#newInstance} factory method to
* create an instance of this fragment.
*/
public class homefragrent extends Fragment {
private RecycleAdapter recycleAdapter;
private RecyclerView recyclerView;
// private RecyclerView.LayoutManager layoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public homefragrent() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment homefragrent.
*/
// TODO: Rename and change types and number of parameters
public static homefragrent newInstance(String param1, String param2) {
homefragrent fragment = new homefragrent();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_homefragrent, container, false);
recyclerView= (view).findViewById(R.id.recycler);
ArrayList<postmodel> exampleimgs = new ArrayList<>();
exampleimgs.add(new postmodel(R.drawable.oner,"post1"));
exampleimgs.add(new postmodel(R.drawable.twor,"post2"));
exampleimgs.add(new postmodel(R.drawable.threer,"post3"));
exampleimgs.add(new postmodel(R.drawable.fourr,"post4"));
exampleimgs.add(new postmodel(R.drawable.fiver,"post5"));
exampleimgs.add(new postmodel(R.drawable.sixr,"post6"));
exampleimgs.add(new postmodel(R.drawable.node,"post7"));
// layoutManager = new LinearLayoutManager(getActivity());
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recycleAdapter = new RecycleAdapter(exampleimgs);
recyclerView.setAdapter(recycleAdapter);
return view;
}
}
///////////////Recycle arapter//////////////////
package com.example.chitchat;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.RecycleViewHolder>{
Context context;
ArrayList<postmodel> imgsl;
public RecycleAdapter(ArrayList<postmodel> imgsl) {
this.context = context;
this.imgsl = imgsl;
}
public class RecycleViewHolder extends RecyclerView.ViewHolder{
TextView textView;
ImageView imageView;
public RecycleViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.textView);
imageView=itemView.findViewById(R.id.imageView);
}
}
#NonNull
#Override
public RecycleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.homefrgmentlayout,parent,false);
RecycleViewHolder recycleViewHolder = new RecycleViewHolder(view);
return recycleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecycleViewHolder holder, int position) {
postmodel currentposition = imgsl.get(position);
holder.imageView.setImageResource(currentposition.getImgs());
holder.textView.setText(currentposition.getComment());
}
#Override
public int getItemCount() {
return imgsl.size();
}
}
//////////////////////////////model class//////////////////////
package com.example.chitchat;
public class postmodel {
private int imgs;
private String comment;
public postmodel(int imgs, String comment) {
this.imgs = imgs;
this.comment = comment;
}
public int getImgs() {
return imgs;
}
public void setImgs(int imgs) {
this.imgs = imgs;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
I feel here it would be
//Pass context from Activity to the adapter
imageView.setImageResource(context.getResources.getDrawables.image)
In Activity
recycleAdapter = new RecycleAdapter(this,exampleimgs);
recyclerView.setAdapter(recycleAdapter);
In Adapter
public RecycleAdapter(Context context, ArrayList<postmodel> imgsl) {
this.context = context;
this.imgsl = imgsl;
}
and then the above line to set image
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.
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();
}
}