Issue
I want to get string in my adapter class on view holder in on click method my app crash when i implement the code write below in on click if(postion==1)
.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private Context context;
String SongURL;
private String[] data;
public Adapter(String[] data){
this.data = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_list_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
String title = data[position];
holder.text.setText(title);
}
@Override
public int getItemCount() {
return data.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView img;
TextView text;
public ViewHolder(final View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.image1);
text = (TextView) itemView.findViewById(R.id.text1);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int postion =getAdapterPosition();
if (postion==0){
String url = "http://sound41.songsbling.link/2016/english-songs/loud-rihanna/12%20-%20Love%20The%20Way%20You%20Lie%20Part%20I%20Bonus%20From%20Us%20%20-%20Loud%20-%20[SongsPK.city].mp3";
Intent intent = new Intent(v.getContext(),player.class);
intent.putExtra("url",url);
v.getContext().startActivity(intent);
}
if (postion==1){
// *This code crashes the app*
String url=Resources.getSystem().getString(R.string.song);
Intent intent = new Intent(v.getContext(),player.class);
intent.putExtra("url",url);
v.getContext().startActivity(intent);
}
}
});
}
}
}
Solution
If you look at the docs you'll see that Resources.getSystem().getStrings
will provide you with system wide strings, not the ones in your application (strings.xml
).
Replace the following line
String url = Resources.getSystem().getString(R.string.song);
with the following.
String url = v.getContext().getResources().getString(R.string.song);
Answered By - Reaz Murshed
Answer Checked By - Timothy Miller (JavaFixing Admin)