how to get string from string.xml in adapter class on click method

被刻印的时光 ゝ 提交于 2021-01-24 01:27:42

问题


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);
                }
            }
        });

        }
    }
}

回答1:


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);


来源:https://stackoverflow.com/questions/49967864/how-to-get-string-from-string-xml-in-adapter-class-on-click-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!