我如何使用从Gson获取的数据在textView中setText

时间:2017-07-10 16:50:21

标签: android android-intent textview gson

我试图用普通的setText方法设置它但是值为null并且textView被设置为空白没有任何单词,我从API获取了json,这里是我的代码 -

public class Child extends AppCompatActivity {

TextView mTitle;
TextView mDescription;
TextView mReleased;
ImageView mCover;
TextView mRating;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_child);

    GsonBuilder gsonBuilder = new GsonBuilder();
    String Obj = getIntent().getStringExtra("movie");
    Movie data = gsonBuilder.create().fromJson(Obj, Movie.class);

    mTitle = (TextView) findViewById(R.id.title);
    mTitle.setText(data.getTitle());
    mDescription = (TextView) findViewById(R.id.description);
    mDescription.setText(data.getDescription());
    mReleased = (TextView) findViewById(R.id.released);
    mReleased.setText(data.getReleased());
    mCover = (ImageView) findViewById(R.id.cover);
    mRating = (TextView) findViewById(R.id.rating);
    mRating.setText(data.getRating());
}}

这是电影课 -

public class Movie {
public String TMDB_IMAGE_PATH = "http://image.tmdb.org/t/p/w500";

private String title;

@SerializedName("poster_path")
private String poster;

@SerializedName("overview")
private String description;

@SerializedName("backdrop_path")
private String released;

private String rating;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getPoster() {
    return TMDB_IMAGE_PATH + poster;
}

public void setPoster(String poster) {
    this.poster = poster;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getReleased() {
    return released;
}

public void setReleased(String released) {
    this.released = released;
}

public String getRating() {
    return rating;
}

public void setRating(String rating) {
    this.rating = rating;
}

public static class result {
    private List<Movie> results;

    public List<Movie> getResults() {
        return results;
    }
}}

最后这是MainActivity中的细节 -

 Movie data = movies.get(position);
                    final Context context = view.getContext();
                    Intent intent = new Intent(context, Child.class);
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    intent.putExtra("movie", gsonBuilder.create().toJson(data, Movie.class));

                    context.startActivity(intent);

2 个答案:

答案 0 :(得分:1)

忘记将Object转换为JSON并返回。相反,通过Movie.class实现Parcelable接口,并将其作为活动之间的对象发送给example。这更快,更清洁,也应该如此。

您可以找到Parcelable的AndroidStudio插件。关注this教程。

答案 1 :(得分:0)

你可以试试这些:

  1. 投放到电影Movie data = (Movie) gsonBuilder.create().fromJson(Obj, Movie.class);
  2. 确保收到的数据符合预期 - &gt;打印String Obj。 Logcat.d("MOVIE APP", Obj);&amp;告诉我结果