在片段中调用json URL

时间:2016-12-12 06:14:15

标签: android

我在片段

中调用json文件

并且我在onsucces方法中遇到错误,即无法解析方法findViewById(Int)。

@Override
public void onSuccess(JSONObject jsonObject, int id) {
    if (id == 10) {

        song_name = jsonObject.optString("name");
        album_name = jsonObject.optString("album");
        duration = jsonObject.optString("duration");
        TextView localTextView1 = (TextView) findViewById(R.id.song_title);
        TextView localTextView2 = (TextView) findViewById(R.id.album_name);
        TextView localTextView3 = (TextView) findViewById(R.id.duration);
        ImageView image = (ImageView) findViewById(R.id.img);
        localTextView1.setText(song_name);
        Picasso.with(getActivity()).load(album_name).into(image);
        localTextView2.setText(Html.fromHtml("" + album_name));
        localTextView3.setText(Html.fromHtml("<b></b> " + duration));

    }
}

2 个答案:

答案 0 :(得分:0)

 TextView localTextView1 = (TextView) view.findViewById(R.id.song_title);
        TextView localTextView2 = (TextView) view.findViewById(R.id.album_name);
        TextView localTextView3 = (TextView) view.findViewById(R.id.duration);
        ImageView image = (ImageView) view.findViewById(R.id.img);

使用视图在片段 OnCreateView()方法中声明这四个视图。 并在onSuccess方法中使用引用。这将解决你的问题 无法解决方法findViewById(Int)问题。

答案 1 :(得分:0)

我在评论中的意思是,

将视图声明为全局变量并在onCreateView中初始化,无需在 onSuccess 中再次初始化它,直接在那里使用。

private TextView localTextView1;
private TextView localTextView2;
private TextView localTextView3;
private ImageView image;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
        localTextView1 = (TextView) view.findViewById(R.id.song_title);
        localTextView2 = (TextView) view.findViewById(R.id.album_name);
        localTextView3 = (TextView) view.findViewById(R.id.duration);
        image = (ImageView) view.findViewById(R.id.img);
        //your code
        return view;
}


@Override
public void onSuccess(JSONObject jsonObject, int id) {
    if (id == 10) {

        song_name = jsonObject.optString("name");
        album_name = jsonObject.optString("album");
        duration = jsonObject.optString("duration");

        localTextView1.setText(song_name);
        Picasso.with(getActivity()).load(album_name).into(image);
        localTextView2.setText(Html.fromHtml("" + album_name));
        localTextView3.setText(Html.fromHtml("<b></b> " + duration));

    }
}