【发布时间】:2020-10-20 20:11:26
【问题描述】:
我尝试从 URL 获取数据并将其传输到 Fragment。该程序可以运行,但结果是什么都没有显示。我认为这是因为我传输数据不正确。但我不知道如何解决它。 我的控制器类:
public class Controller implements Callback<News> {
private static final String BASE_URL = "https://news.com/wwer/";
private ApiInterface apiInterface;
private MainActivity mainActivity;
public Controller(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
public void start() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiInterface = retrofit.create(ApiInterface.class);
Call<News> news = apiInterface.getNews();
news.enqueue(this);
}
@Override
public void onResponse(Call<News> call, Response<News> response) {
News news = response.body();
String sourceName = news.getSources().get(1).getName();
Bundle bundle = new Bundle();
bundle.putString("sourceName", sourceName);
FragmentManager fm = mainActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
NameFragment fragmentCurrent = new NameFragment();
fragmentCurrent.setArguments(bundle);
ft.add(R.id.fragment,fragmentCurrent);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
@Override
public void onFailure(Call<News> call, Throwable t) {
Log.d("error", "can't parse data: ", t);
}
}
和我的片段类:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.name_fragment, container, false);
TextView textView = view.findViewById(R.id.news_names_list);
Bundle bundle = new Bundle();
String sourcNam = bundle.getString("sourceName");
textView.setText(sourcNam);
return view;
}
}
【问题讨论】:
标签: android android-fragments retrofit