我具有Mainactivity,在其中我使用了多个片段,这些片段以json格式在线时检索图像和文本,并在设备脱机时存储和更新信息,从而显示相同的存储数据。
问题是,当我在片段之间滑动时,每次它开始从在线获取数据时都在线,这需要很多时间。所以这很昧。 我正在寻找一种解决方案,当打开应用程序时,仅查找在线数据,然后从存储的数据库中显示数据。
下面是我的代码
public class technology extends Fragment implements techTAdapter.FlowerClickListener, techTFetchListener {
private techTManager mManager;
private techTAdapter mFlowerAdapter;
private techTDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
loadFlowerFeed();
return view;
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage("Loading information..");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
public void getFeed() {
Call<List<techT>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<techT>>() {
@Override
public void onResponse(Call<List<techT>> call, Response<List<techT>> response) {
if (response.isSuccessful()) {
List<techT> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
techT flower = flowerList.get(i);
technology.SaveIntoDatabase task = new technology.SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
@Override
public void onFailure(Call<List<techT>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public class SaveIntoDatabase extends AsyncTask<techT, Void, Void> {
private final String TAG = technology.SaveIntoDatabase.class.getSimpleName();
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(techT... params) {
techT flower = params[0];
try {
InputStream stream = new URL(techTConstant.HTTP.BASE_URL + "/photos/" + flower.getPhoto()).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
flower.setPicture(bitmap);
mDatabase.addFlower(flower);
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
,并提前谢谢。让我知道是否需要更多信息。