我希望能够从API中加载信息到Fragment
。
我使用getSupportLoaderManager()
,但是出现了一个错误:
无法解决方法:getSupportLoaderManager()
我查找资料后发现需要使用onActivityCreated()
,但是我遇到了NullPointerException
。
您能帮助我解决这个问题吗?
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class Business extends Fragment implements LoaderManager.LoaderCallbacks<String> {
ListView listView;
public Business() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_business, container, false);
listView = view.findViewById(R.id.list_item);
getSupportLoaderManager().initLoader(0, null, getContext()).forceLoad();
return view;
}
@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
return null;
}
@Override
public void onLoadFinished(Loader<String> loader, String data) {
if (data != null && !data.isEmpty())
updateUI(data);
else
Toast.makeText(getContext(), "no internet", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoaderReset(Loader<String> loader) {
}
private void updateUI(String data) {
try {
final ArrayList<ResultOfArtBusiness> results = new ArrayList<>();
JSONObject root = new JSONObject(data);
JSONObject secondObject = root.getJSONObject("response");
JSONArray firstArray = secondObject.getJSONArray("results");
for (int i = 0; i < firstArray.length(); i++) {
JSONObject objectInArray = firstArray.getJSONObject(i);
String webPublicationDate;
if (objectInArray.has("webPublicationDate"))
webPublicationDate = objectInArray.getString("webPublicationDate");
else webPublicationDate = null;
String webTitle;
if (objectInArray.has("webTitle"))
webTitle = objectInArray.getString("webTitle");
else webTitle = null;
String webUrl;
if (objectInArray.has("webUrl"))
webUrl = objectInArray.getString("webUrl");
else webUrl = null;
ResultOfArtBusiness resultOfArticle = new ResultOfArtBusiness(webTitle, webPublicationDate, webUrl);
results.add(resultOfArticle);
}
NewsAdapterBusiness adapter = new NewsAdapterBusiness(getContext(), R.layout.item_design, results);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
onActivityCreated()
的代码,所以我不理解你问题中的这一部分。 - Bö macht Blau