I have done various ways, but to no avail
DataSource
public class NetReqDataSourceFactory extends DataSource.Factory {
private static final String TAG = NetReqDataSourceFactory.class.getSimpleName();
private MutableLiveData<NetReqPageKeyedDataSource> networkStatus;
private NetReqPageKeyedDataSource moviesPageKeyedDataSource;
public NetReqDataSourceFactory(Context context, String status) {
this.networkStatus = new MutableLiveData<>();
moviesPageKeyedDataSource = new NetReqPageKeyedDataSource(context, status);
}
#Override
public DataSource create() {
networkStatus.postValue(moviesPageKeyedDataSource);
return moviesPageKeyedDataSource;
}
public MutableLiveData<NetReqPageKeyedDataSource> getNetworkStatus() {
return networkStatus;
}
public ReplaySubject<ReqDataList> getData() {
return moviesPageKeyedDataSource.getData();
}
}
PageKeyedDataSource
public class NetReqPageKeyedDataSource extends PageKeyedDataSource<String, ReqDataList> {
private static final String TAG = NetReqPageKeyedDataSource.class.getSimpleName();
private final MutableLiveData networkState;
private final ReplaySubject<ReqDataList> moviesObservable;
private final ConnectionServer connectionServer;
private final String status;
private final MasterRepository repository;
NetReqPageKeyedDataSource(Context context, String status) {
networkState = new MutableLiveData();
connectionServer = new ConnectionServer(Util.getApiWithAuth(context, (new ArrayList<ReqDataList>()).getClass(), new ReqJsonDeserializer()));
moviesObservable = ReplaySubject.create();
this.status = status;
this.repository = MasterRepository.getInstance(context);
}
public MutableLiveData getNetworkState() {
return networkState;
}
public ReplaySubject<ReqDataList> getData() {
return moviesObservable;
}
#Override
public void loadInitial(#NonNull LoadInitialParams<String> params, #NonNull final LoadInitialCallback<String, ReqDataList> callback) {
Log.i(TAG, "Loading Initial Rang, Count " + params.requestedLoadSize);
Log.i(TAG, "Loading Initial, Status " + status);
networkState.postValue(NetworkState.FIRST_LOADING);
connectionServer.getReqByPage(1, status).enqueue(new Callback<ArrayList<ReqDataList>>() {
#Override
public void onResponse(Call<ArrayList<ReqDataList>> call, Response<ArrayList<ReqDataList>> response) {
if (response.isSuccessful()) {
callback.onResult(response.body(), Integer.toString(1), Integer.toString(2));
networkState.postValue(NetworkState.LOADED);
if (response.body().size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
response.body().forEach(moviesObservable::onNext);
} else {
for (ReqDataList data : response.body()) {
moviesObservable.onNext(data);
}
}
} else {
networkState.postValue(new NetworkState(NetworkState.Status.FIRST_FAILED, "Nothing here yet, pull to refresh & try again"));
}
} else {
Log.e("API CALL", response.message());
networkState.postValue(new NetworkState(NetworkState.Status.FIRST_FAILED, response.message()));
}
}
#Override
public void onFailure(Call<ArrayList<ReqDataList>> call, Throwable t) {
String errorMessage;
if (t.getMessage() == null) {
errorMessage = "unknown error";
} else {
errorMessage = t.getMessage();
}
networkState.postValue(new NetworkState(NetworkState.Status.FIRST_FAILED, errorMessage));
callback.onResult(new ArrayList<>(), Integer.toString(1), Integer.toString(2));
}
});
}
#Override
public void loadAfter(#NonNull LoadParams<String> params, final #NonNull LoadCallback<String, ReqDataList> callback) {
Log.i(TAG, "Loading page " + params.key );
networkState.postValue(NetworkState.LOADING);
final AtomicInteger page = new AtomicInteger(0);
try {
page.set(Integer.parseInt(params.key));
}catch (NumberFormatException e){
e.printStackTrace();
}
Call<ArrayList<ReqDataList>> callBack = connectionServer.getReqByPage(page.get(), status);
callBack.enqueue(new Callback<ArrayList<ReqDataList>>() {
#Override
public void onResponse(Call<ArrayList<ReqDataList>> call, Response<ArrayList<ReqDataList>> response) {
if (response.isSuccessful()) {
callback.onResult(response.body(), Integer.toString(page.get() + 1));
networkState.postValue(NetworkState.LOADED);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
response.body().forEach(moviesObservable::onNext);
} else {
for (ReqDataList data : response.body()) {
moviesObservable.onNext(data);
}
}
} else {
networkState.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
Log.e("API CALL", response.message());
}
}
#Override
public void onFailure(Call<ArrayList<ReqDataList>> call, Throwable t) {
String errorMessage;
if (t.getMessage() == null) {
errorMessage = "unknown error";
} else {
errorMessage = t.getMessage();
}
networkState.postValue(new NetworkState(NetworkState.Status.FAILED, errorMessage));
callback.onResult(new ArrayList<>(), Integer.toString(page.get()));
}
});
}
#Override
public void loadBefore(#NonNull LoadParams<String> params, #NonNull LoadCallback<String, ReqDataList> callback) {
}
}
PagedList.Config
public class ReqNetwork {
final private static String TAG = ReqNetwork.class.getSimpleName();
final private LiveData<PagedList<ReqDataList>> moviesPaged;
final private LiveData<NetworkState> networkState;
public ReqNetwork(NetReqDataSourceFactory dataSourceFactory, PagedList.BoundaryCallback<ReqDataList> boundaryCallback) {
PagedList.Config pagedListConfig = (new PagedList.Config.Builder())
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(20)
.setPageSize(10)
.build();
networkState = Transformations.switchMap(
dataSourceFactory.getNetworkStatus(),
(Function<NetReqPageKeyedDataSource, LiveData<NetworkState>>) NetReqPageKeyedDataSource::getNetworkState
);
Executor executor = Executors.newFixedThreadPool(3);
LivePagedListBuilder livePagedListBuilder = new LivePagedListBuilder(dataSourceFactory, pagedListConfig);
moviesPaged = livePagedListBuilder.
setFetchExecutor(executor).
setBoundaryCallback(boundaryCallback).
build();
}
public LiveData<PagedList<ReqDataList>> getPagedMovies() {
return moviesPaged;
}
public LiveData<NetworkState> getNetworkState() {
return networkState;
}
}
LocalDataSource
public class DbReqDataSourceFactory extends DataSource.Factory {
private static final String TAG = DbReqDataSourceFactory.class.getSimpleName();
private DbReqPageKeyedDataSource moviesPageKeyedDataSource;
public DbReqDataSourceFactory(ReqDataDao dao, String filterStatus) {
moviesPageKeyedDataSource = new DbReqPageKeyedDataSource(dao, filterStatus);
}
#Override
public DataSource create() {
return moviesPageKeyedDataSource;
}
}
LocalPageKeyedDataSource
public class DbReqPageKeyedDataSource extends PageKeyedDataSource<String, ReqDataList> {
public static final String TAG = DbReqPageKeyedDataSource.class.getSimpleName();
private final ReqDataDao dataDao;
private String filterStatus;
public DbReqPageKeyedDataSource(ReqDataDao dao, String status) {
dataDao = dao;
filterStatus = status;
}
#Override
public void loadInitial(#NonNull LoadInitialParams<String> params, #NonNull final LoadInitialCallback<String, ReqDataList> callback) {
Log.i(TAG, "Loading Initial Rang, Count " + params.requestedLoadSize);
Log.w(TAG, "loadInitial: " + filterStatus);
List<ReqDataList> data = null;
if (filterStatus == null) {
data = dataDao.getListAll();
} else {
data = dataDao.getListAllByStatus(filterStatus);
}
if(data.size() != 0) {
callback.onResult(data, "0", "1");
}
}
#Override
public void loadAfter(#NonNull LoadParams<String> params, final #NonNull LoadCallback<String, ReqDataList> callback) {
}
#Override
public void loadBefore(#NonNull LoadParams<String> params, #NonNull LoadCallback<String, ReqDataList> callback) {
}
}
Repository
public LiveData<PagedList<ReqDataList>> getDataReqPage(Context context, String status){
initReqPageDao(status);
NetReqDataSourceFactory dataSourceFactory = new NetReqDataSourceFactory(context, status);
network = new ReqNetwork(dataSourceFactory, reqBoundaryCallback);
reqLiveDataMerger = new MediatorLiveData<>();
reqLiveDataMerger.addSource(network.getPagedMovies(), value -> {
reqLiveDataMerger.setValue(value);
Log.d(TAG, value.toString());
});
dataSourceFactory.getData().
observeOn(Schedulers.io()).
subscribe(item -> {
ReqData reqData = new ReqData();
reqData.req_sid = item.req_sid;
reqData.req_uid = item.req_uid;
reqData.req_total = item.req_total;
reqData.req_pemda = item.req_pemda;
reqData.req_lon = item.req_lon;
reqData.req_lat = item.req_lat;
reqData.req_address = item.req_address;
reqData.req_remark = item.req_remark;
reqData.address_id = item.address_id;
reqData.post_by = item.post_by;
reqData.post_date = item.post_date;
reqData.update_by = item.update_by;
reqData.update_date = item.update_date;
reqData.post_status = 1;
database.dataReqDao().insert(reqData);
});
return reqLiveDataMerger;
}
public void initReqPageDao(String status) {
PagedList.Config pagedListConfig = (new PagedList.Config.Builder()).setEnablePlaceholders(false)
.setInitialLoadSizeHint(Integer.MAX_VALUE).setPageSize(Integer.MAX_VALUE).build();
Executor executor = Executors.newFixedThreadPool(3);
DbReqDataSourceFactory dataSourceFactory = new DbReqDataSourceFactory(database.dataReqDao(), status);
LivePagedListBuilder livePagedListBuilder = new LivePagedListBuilder(dataSourceFactory, pagedListConfig);
reqPaged = livePagedListBuilder.setFetchExecutor(executor).build();
}
private PagedList.BoundaryCallback<ReqDataList> reqBoundaryCallback = new PagedList.BoundaryCallback<ReqDataList>() {
#Override
public void onZeroItemsLoaded() {
super.onZeroItemsLoaded();
reqLiveDataMerger.addSource(getReqData(), value -> {
reqLiveDataMerger.setValue(value);
reqLiveDataMerger.removeSource(getReqData());
});
}
};
public LiveData<PagedList<ReqDataList>> getReqData() {
return reqPaged;
}
ViewModel
public LiveData<PagedList<ReqDataList>> getReqDataPaged(String status) {
return getRepository().getDataReqPage(getContext(), status);
}
public LiveData<NetworkState> getNetworkState() {
return getRepository().getNetworkState();
}
Did you guys find my fault?
I load data using a Fragment inside the ViewPager
public class ReqListFragment extends BaseFragment<FragmentReqListBinding, ReqListViewModel> implements ReqListViewModel.Navigator {
#Inject
ConnectionServer server;
#Inject
MasterRepository repository;
private FragmentReqListBinding binding;
private ReqListViewModel viewModel;
private String status;
private boolean hasLoaded = false;
#Override
public int getBindingVariable() {
return 0;
}
#Override
public int getLayoutId() {
return R.layout.fragment_req_list;
}
#Override
public ReqListViewModel getViewModel() {
return viewModel;
}
public ReqListFragment newInstance(String status) {
ReqListFragment fragment = new ReqListFragment();
Bundle bundle = new Bundle();
bundle.putString(Constants.STATUS, status);
fragment.setArguments(bundle);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
AndroidSupportInjection.inject(this);
binding = getViewDataBinding();
viewModel = ViewModelProviders.of(this, new ReqListViewModel.ModelFactory(getBaseActivity(), server, repository)).get(ReqListViewModel.class);
viewModel.setNavigator(this);
status = getArguments().getString(Constants.STATUS);
viewModel.filterStatus.postValue(status);
if (status.equals(Constants.ALL)) {
loadData(status);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
binding.swipe.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorApprovedBg));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
binding.recyclerView.setLayoutManager(linearLayoutManager);
binding.swipe.setOnRefreshListener(()->loadData(status));
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getView() != null && isVisibleToUser && !hasLoaded && !status.equals(Constants.ALL)) {
loadData(status);
}
}
private void loadData(String status) {
binding.shimmerViewContainer.startShimmer();
binding.shimmerViewContainer.setVisibility(View.VISIBLE);
final ReqListAdapter pageListAdapter = new ReqListAdapter(viewModel);
viewModel.getReqDataPaged(status).observe(this, pageListAdapter::submitList);
viewModel.getNetworkState().observe(this, networkState -> {
pageListAdapter.setNetworkState(networkState);
binding.setState(networkState);
});
binding.recyclerView.setAdapter(pageListAdapter);
hasLoaded = true;
}
#Override
public void onItemClick(String item) {
Intent intent = new Intent(getBaseActivity(), ReqViewActivity.class);
intent.putExtra(Constants.SID, item);
startActivity(intent);
}
}
In other conditions I succeed if I move the code initReqPageDao to the RoomDatabase class,
but i am confused about sending status for filter
Thank you all for your help, I hope I find the error and a solution
Related
i am implementing paging library in android all works fine if item of all pages are the same. When item of last page items size is 1 rather then 10 it gives a exception. i am using paging library 2.1.1 with androidx.
Exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dasfilm.azzeddine.dasfilm, PID: 22472
java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.get(ArrayList.java:437)
at androidx.paging.PagedStorage.get(PagedStorage.java:152)
at androidx.paging.PagedList.get(PagedList.java:384)
at androidx.paging.AsyncPagedListDiffer.getItem(AsyncPagedListDiffer.java:206)
at androidx.paging.PagedListAdapter.getItem(PagedListAdapter.java:156)
at com.dasfilm.azzeddine.dasfilm.Views.Adapters.FreshoneProductPaggingAdapter.onBindViewHolder(FreshoneProductPaggingAdapter.java:56)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at androidx.recyclerview.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:286)
at androidx.recyclerview.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:343)
at androidx.recyclerview.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:359)
at androidx.recyclerview.widget.GapWorker.prefetch(GapWorker.java:366)
at androidx.recyclerview.widget.GapWorker.run(GapWorker.java:397)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
DataSource Class : This is my data source class with is getting data from web service
public class MoviesInTheaterDataSource extends PageKeyedDataSource<Integer, FreshProduct> {
private static final String TAG = "MoviesInTheaterDataSou";
private ProductApiCall tmdbWebService;
private MutableLiveData<NetworkState> networkState;
private MutableLiveData<NetworkState> initialLoading;
private Executor retryExecutor;
public MoviesInTheaterDataSource(Executor retryExecutor,ProductApiCall webService) {
tmdbWebService = webService;
networkState = new MutableLiveData<>();
initialLoading = new MutableLiveData<>();
this.retryExecutor = retryExecutor;
}
public MutableLiveData<NetworkState> getNetworkState() {
return networkState;
}
public MutableLiveData getInitialLoading() {
return initialLoading;
}
#Override
public void loadInitial(#NonNull final LoadInitialParams<Integer> params, #NonNull final LoadInitialCallback<Integer, FreshProduct> callback) {
Log.d(TAG, "loadInitial: ");
initialLoading.postValue(NetworkState.LOADING);
networkState.postValue(NetworkState.LOADING);
tmdbWebService.getProductList(1,"","",1);
tmdbWebService.SetListenersProduct(new ProductApiCall.ListenersProduct() {
#Override
public void onSuccess(List<FreshProduct> itemList, int totalPageCount) {
initialLoading.postValue(NetworkState.LOADING);
int loadsize = params.requestedLoadSize;
callback.onResult(itemList, 1, 2);
networkState.postValue(NetworkState.LOADED);
}
});
}
#Override
public void loadBefore(#NonNull LoadParams<Integer> params, #NonNull LoadCallback<Integer, FreshProduct> callback) {
}
#Override
public void loadAfter(#NonNull final LoadParams<Integer> params, #NonNull final LoadCallback<Integer, FreshProduct> callback) {
networkState.postValue(NetworkState.LOADING);
tmdbWebService.getProductList(1,"","",params.key);
tmdbWebService.SetListenersProduct(new ProductApiCall.ListenersProduct() {
#Override
public void onSuccess(List<FreshProduct> itemList, int totalPageCount) {
initialLoading.postValue(NetworkState.LOADING);
networkState.postValue(NetworkState.LOADED);
callback.onResult(itemList, params.key+1);
networkState.postValue(NetworkState.LOADED);
}
});
}
}
DataSource Factory Class
public class MoviesInTheaterDataSource extends PageKeyedDataSource<Integer, FreshProduct> {
private static final String TAG = "MoviesInTheaterDataSou";
private ProductApiCall tmdbWebService;
private MutableLiveData<NetworkState> networkState;
private MutableLiveData<NetworkState> initialLoading;
private Executor retryExecutor;
public MoviesInTheaterDataSource(Executor retryExecutor,ProductApiCall webService) {
tmdbWebService = webService;
networkState = new MutableLiveData<>();
initialLoading = new MutableLiveData<>();
this.retryExecutor = retryExecutor;
}
public MutableLiveData<NetworkState> getNetworkState() {
return networkState;
}
public MutableLiveData getInitialLoading() {
return initialLoading;
}
#Override
public void loadInitial(#NonNull final LoadInitialParams<Integer> params, #NonNull final LoadInitialCallback<Integer, FreshProduct> callback) {
Log.d(TAG, "loadInitial: ");
initialLoading.postValue(NetworkState.LOADING);
networkState.postValue(NetworkState.LOADING);
tmdbWebService.getProductList(1,"","",1);
tmdbWebService.SetListenersProduct(new ProductApiCall.ListenersProduct() {
#Override
public void onSuccess(List<FreshProduct> itemList, int totalPageCount) {
initialLoading.postValue(NetworkState.LOADING);
int loadsize = params.requestedLoadSize;
callback.onResult(itemList, 1, 2);
networkState.postValue(NetworkState.LOADED);
}
});
}
#Override
public void loadBefore(#NonNull LoadParams<Integer> params, #NonNull LoadCallback<Integer, FreshProduct> callback) {
}
#Override
public void loadAfter(#NonNull final LoadParams<Integer> params, #NonNull final LoadCallback<Integer, FreshProduct> callback) {
networkState.postValue(NetworkState.LOADING);
tmdbWebService.getProductList(1,"","",params.key);
tmdbWebService.SetListenersProduct(new ProductApiCall.ListenersProduct() {
#Override
public void onSuccess(List<FreshProduct> itemList, int totalPageCount) {
initialLoading.postValue(NetworkState.LOADING);
networkState.postValue(NetworkState.LOADED);
callback.onResult(itemList, params.key+1);
networkState.postValue(NetworkState.LOADED);
}
});
}
}
ViewModel Class
public class MoviesInTheaterViewModel extends ViewModel {
private static final String TAG = "TheaterViewModel";
private LiveData<PagedList<FreshProduct>> moviesInTheaterList;
private LiveData<NetworkState> networkStateLiveData;
private Executor executor;
private LiveData<MoviesInTheaterDataSource> dataSource;
public MoviesInTheaterViewModel() {
Log.d(TAG, "MoviesInTheaterViewModel: ");
executor = Executors.newFixedThreadPool(5);
ProductApiCall webService = new ProductApiCall(MyApp.getInstance().getApplicationContext());
MoviesInTheaterDataSourceFactory factory = new MoviesInTheaterDataSourceFactory(executor,webService);
dataSource = factory.getMutableLiveData();
networkStateLiveData = Transformations.switchMap(factory.getMutableLiveData(), new Function<MoviesInTheaterDataSource, LiveData<NetworkState>>() {
#Override
public LiveData<NetworkState> apply(MoviesInTheaterDataSource source) {
Log.d(TAG, "apply: network change");
return source.getNetworkState();
}
});
PagedList.Config pageConfig = (new PagedList.Config.Builder())
.setEnablePlaceholders(false)
.setPageSize(10)
.build();
moviesInTheaterList = (new LivePagedListBuilder<Integer,FreshProduct>(factory,pageConfig))
.setFetchExecutor(executor)
.build();
}
public LiveData<PagedList<FreshProduct>> getMoviesInTheaterList() {
Log.d(TAG, "getMoviesInTheaterList: ");
return moviesInTheaterList;
}
public LiveData<NetworkState> getNetworkStateLiveData() {
return networkStateLiveData;
}
}
Activity Class
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private MoviesInTheaterViewModel mMoviesViewModel;
private RecyclerView mRecyclerView;
private FreshoneProductPaggingAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: ");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.list);
adapter = new FreshoneProductPaggingAdapter(this);
mMoviesViewModel = ViewModelProviders.of(this).get(MoviesInTheaterViewModel.class);
mMoviesViewModel.getMoviesInTheaterList().observe(this, new Observer<PagedList<FreshProduct>>() {
#Override
public void onChanged(#Nullable PagedList<FreshProduct> movies) {
Log.d(TAG, "onChanged: "+movies.size());
adapter.submitList(movies);
}
});
mMoviesViewModel.getNetworkStateLiveData().observe(this, new Observer<NetworkState>() {
#Override
public void onChanged(#Nullable NetworkState networkState) {
Log.d(TAG, "onChanged: network state changed");
adapter.setNetworkState(networkState);
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
mRecyclerView.setAdapter(adapter);
}
}
Paging2 doesn't support variable page sizes, you need to migrate to Paging3 (still in alpha) for that functionality. This is partially due to how tiling support was implemented, but Paging3 has rewritten things from the ground up to remove this constraint.
Can any one help me whats wrong in my code
unable to save ArrayList document value in shared Preference
getting null value in Debug of Array List Document
please help me
Thanks in advance
here is my JSON response
{
"errCode": 0,
"message": "Success",
"responseDestinationDocument": [
{
"name": "United Arab Emirates",
"document": [
{
"name": "Passport Front",
"id": "2",
"notes": [
{
"name": "Upload colored passport copies."
},
{
"name": "Passport should be valid 6 months from the date of entry in Sri Lanka."
},
{
"name": "DDDDDDD"
}
]
},
{
"name": "Passport Back",
"id": "3",
"notes": [
{
"name": "Upload colored passport copy."
}
]
},
{
"name": "Photograph",
"id": "4",
"notes": [
{
"name": "Upload photograph with white background"
}
]
}
]
}
]
}
I want to save ArrayList document value in shared Preference
Here is activity code
public class UploadDocumentsActivity extends AppCompatActivity {
private MyCustomAdapter myCustomAdapter;
protected ViewDialog viewDialog;
String destination_id, start_date, end_date, no_of_travellers, destination_name, package_id, radioSexButton, booking_id, count_index;
private List<ResponseBookingDocument> responseBookingDocumentArrayList;
private List<Document> document1ArrayList;
Document document1;
private RecyclerView recyclerView_Identity;
private static final int SELECT_PICTURE = 100;
private static final int STORAGE_PERMISSION_CODE = 123;
final Handler handler = new Handler();
final int delay = 1000; //milliseconds
private ImageView imageView1;
String selectedImagePath;
private Uri filePath_1;
private boolean isOnTag = false;
Bitmap bitmap;
preivate ArrayList<String> nameList = new ArrayList<>();
preivate ArrayList<String> idList = new ArrayList<>();
TextView continueTextView;
private Runnable mToast = new Runnable() {
#Override
public void run() {
// documentRequiredCall();
handler.postDelayed(this, 1000);
}
};
ResponseBookInfo responseBookInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_documents);
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
// Log.e("document1", document1.getId() + "");
try {
document1 = PrefUtils.getDocId(UploadDocumentsActivity.this);
Log.e("document1", document1.getId() + "");
} catch (Exception e) {
e.printStackTrace();
}
Intent i = getIntent();
destination_id = i.getStringExtra("destination_id");
package_id = i.getStringExtra("package_id");
radioSexButton = i.getStringExtra("radioSexButton");
booking_id = i.getStringExtra("booking_id");
count_index = i.getStringExtra("count_index");
Log.e("BookING", booking_id + "");
destination_name = i.getStringExtra("destination_name");
start_date = i.getStringExtra("start_date");
end_date = i.getStringExtra("end_date");
no_of_travellers = i.getStringExtra("no_of_travellers");
recyclerView_Identity = findViewById(R.id.recyclerView_Identity);
continueTextView = findViewById(R.id.continueTextView);
LinearLayoutManager layoutManager = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity.setLayoutManager(layoutManager);
recyclerView_Identity.setHasFixedSize(true);
continueTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UploadDocumentsActivity.this, ApplicationFormActivity.class);
i.putExtra("booking_id", booking_id);
i.putExtra("count_index", count_index);
i.putExtra("start_date", start_date);
i.putExtra("end_date", end_date);
startActivity(i);
}
});
documentRequiredCall();
//
Log.e("Values", destination_id + " " + package_id + " " + end_date + " " + no_of_travellers + " " + count_index + "");
}
public void documentRequiredCall() {
Call<DocumentFetchModel> call = RetrofitClient
.getInstance().getApi().documentFetchModel(booking_id, count_index);
showProgressDialog();
call.enqueue(new Callback<DocumentFetchModel>() {
#Override
public void onResponse(Call<DocumentFetchModel> call, retrofit2.Response<DocumentFetchModel> response) {
final DocumentFetchModel documentFetchModel = response.body();
hideProgressDialog();
PrefUtils.setDocId(documentFetchModel.getResponseBookingDocument().get(0).getDocument(), UploadDocumentsActivity.this);
int size = documentFetchModel.getResponseBookingDocument().get(0).getDocument().size();
for (int i = 0; i < size; i++) {
nameList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getName());
idList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getId());
}
//here is app preference class saving the values
AppPreference.setNameList(this, nameList);
AppPreference.setIdList(this, idLIst);
if (documentFetchModel.getErrCode().booleanValue() == true) {
responseBookingDocumentArrayList = new ArrayList<ResponseBookingDocument>();
try {
Log.e("Booking_Document", new Gson().toJson(response.body()));
document1ArrayList = documentFetchModel.getResponseBookingDocument().get(0).getDocument();
myCustomAdapter = new MyCustomAdapter(document1ArrayList);
recyclerView_Identity.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(UploadDocumentsActivity.this, documentFetchModel.getMessage() + "", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<DocumentFetchModel> call, Throwable t) {
hideProgressDialog();
Toast.makeText(UploadDocumentsActivity.this, t.getMessage() + "", Toast.LENGTH_LONG).show();
Log.e("Error", t.getMessage() + "");
}
});
}
protected void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<Document> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textTitle;
public ImageView imageUpload, imageFetch;
private List<Note> noteArrayList;
private MyCustomAdapter2 myCustomAdapter2;
private RecyclerView recyclerView_Identity_Bullets;
public MyViewHolder(View view) {
super(view);
textTitle = view.findViewById(R.id.textTitle);
imageUpload = view.findViewById(R.id.imageUpload);
imageFetch = view.findViewById(R.id.imageFetch);
recyclerView_Identity_Bullets = view.findViewById(R.id.recyclerView_Identity_Bullets);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity_Bullets.setLayoutManager(layoutManager2);
recyclerView_Identity_Bullets.setHasFixedSize(true);
}
}
public MyCustomAdapter(List<Document> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_document, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Document datum = moviesList.get(position);
holder.textTitle.setText(datum.getName() + "");
holder.noteArrayList = datum.getNotes();
holder.myCustomAdapter2 = new MyCustomAdapter2(holder.noteArrayList);
holder.recyclerView_Identity_Bullets.setAdapter(holder.myCustomAdapter2);
if (datum.getImageName().equals("")) {
holder.imageFetch.setVisibility(View.GONE);
holder.imageUpload.setVisibility(View.VISIBLE);
holder.imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(UploadDocumentsActivity.this, datum.getId(), Toast.LENGTH_SHORT).show();
}
});
} else {
holder.imageUpload.setVisibility(View.GONE);
holder.imageFetch.setVisibility(View.VISIBLE);
Picasso.with(UploadDocumentsActivity.this).load(datum.getImageName() + "").into(holder.imageFetch);
}
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
public class MyCustomAdapter2 extends RecyclerView.Adapter<MyCustomAdapter2.MyViewHolder> {
private List<Note> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textBullet;
public MyViewHolder(View view) {
super(view);
textBullet = view.findViewById(R.id.textBullet);
}
}
public MyCustomAdapter2(List<Note> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_bullets_and_image, parent, false);
return new MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Note datum = moviesList.get(position);
holder.textBullet.setText(" \u25CF " + datum.getName() + "");
Log.e("textBullet", datum.getName() + "");
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
#Override
public void onStart() {
super.onStart();
mToast.run();
}
#Override
public void onStop() {
super.onStop();
handler.removeCallbacks(mToast);
}
}
Here is Model Class
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
public class ResponseBookingDocument {
#SerializedName("name")
#Expose
private String name;
#SerializedName("document")
#Expose
private List<Document> document = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Document> getDocument() {
return document;
}
public void setDocument(List<Document> document) {
this.document = document;
}
}
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
Here is ComplexPreference
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "complex_preferences";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context,
String namePreferences, int mode) {
// if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context,
namePreferences, mode);
// }
return complexPreferences;
}
public void putObject(String key, Object object) {
if(object == null){
throw new IllegalArgumentException("object is null");
}
if(key.equals("") || key == null){
throw new IllegalArgumentException("key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public void clearObject() {
editor.clear();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
} else {
try{
return GSON.fromJson(gson, a);
} catch (Exception e) {
throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
}
}
}
}
Here is PrefUtils Class
public class PrefUtils {
public static DocumentFetchModel getDoc(Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
DocumentFetchModel currentUser = complexPreferences.getObject("docs", DocumentFetchModel.class);
return currentUser;
}
public static void setDoc(DocumentFetchModel currentUser, Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
complexPreferences.putObject("docs", currentUser);
complexPreferences.commit();
}
}
you can save list in sharedpreference like this:-
public class AppPreferences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("nameList", null);
}
public static void setName(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
public static void clearNameList(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
}
to set list :-
setCamEval(activity, list);
to get list :-
getCamEval(this);
I have a FirebaseRecyclerAdapter fetching data from the firebase database but when I am trying to access firebase data the getter method of the POJO returns null. I am able to get the database reference key.
final Query beveragesQuery = mDatabaseReference.child(FirebaseValues.PRODUCTS)
.child(FirebaseValues.BEVERAGES);
FirebaseRecyclerOptions<GenericProductModel> beveragesOptions =
new FirebaseRecyclerOptions.Builder<GenericProductModel>()
.setQuery(beveragesQuery, GenericProductModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<GenericProductModel, Combos.MovieViewHolder>(
beveragesOptions
) {
#NonNull
#Override
public Combos.MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_cardview_layout, parent, false);
return new Combos.MovieViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Combos.MovieViewHolder viewHolder, int position, #NonNull GenericProductModel model) {
Log.d(TAG, "Item received:"+getRef(position).getKey());
String json = new Gson().toJson(model);
Log.d(TAG, "Item received:"+ json);
Log.d(TAG, "Item received:"+ model.toString());
if (tv_no_item.getVisibility() == View.VISIBLE) {
tv_no_item.setVisibility(View.GONE);
}
Log.d(TAG, "card name:"+model.getCardname());
viewHolder.cardname.setText(model.getCardname());
viewHolder.cardprice.setText("₹ " + Float.toString(model.getCardprice()));
Picasso.get().load(model.getCardimage()).into(viewHolder.cardimage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Beverages.this, IndividualProduct.class);
intent.putExtra("product", getItem(position));
startActivity(intent);
}
});
}
#Override
public void onError(DatabaseError e) {
Log.e(TAG, "RV Adapter, Error occurred: " + e.getMessage());
}
};
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
adapter.startListening();
mRecyclerView.setAdapter(adapter);
}
My POJO or model class is
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
I am implementing Serializable because I am sending this data as an intent to other activity.
Added some more log options for clearity
When I run the app the log output I am getting is:
03-17 15:05:55.200 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received, received:1
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:{"a":0,"e":0.0}
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:com.vdeveloper.chaisutta.b.a#63d3fc
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: card name:null
Database Screenshot:
I have found a solution myself. The problem was with my POJO. As this project was on androidx I need to add the annotation "#Keep" to stop the compiler from removing methods which it thinks are redundant.
import java.io.Serializable;
import androidx.annotation.Keep;
#Keep
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
Thanks, everyone for helping
You are getting null because all your values are null since you are returning in each getter this.fieldName instead of the fieldName. To solve this, please change your getters to:
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
See, there is no this anymore.
This is Fist time i'm asking question!! so bear with me.
The application is project(popular movie stage 2) from udacity where i need to fetch info of movies like tilte or poster_path or backdrop_path.
so when i fetch data from json it works perfectly fine but when i add another argument String backdrop in my Movies.java class.then getmBackdrop() shows empty and i couldn't get the data of backdrop overview and vote.but if i delete backdrop from constructor than it works fine. i dont know what is happening please help me.
this is Movies.javaclass
public class Movies implements Parcelable {
//Movies Data
public long mID;
private String mPosterPath;
private String mReleaseDate;
private String mTitle;
private String mVote;
private String mOverview;
private String mBackdrop;
private ArrayList<Trailers> trailers;
private ArrayList<Reviews> reviews;
public Movies() {
}
public Movies(String title, String releaseDate, String posterPath,
String backdrop,String vote, String overview) {
// this.mID=id;
this.mTitle = title;
this.mReleaseDate = releaseDate;
this.mPosterPath = posterPath;
this.mBackdrop = backdrop;
this.mVote = vote;
this.mOverview = overview;
this.trailers = new ArrayList<>();
this.reviews = new ArrayList<>();
}
public long getID(){ return mID ;}
public String getmBackdrop() { return mBackdrop; }
public String getPosterPath() {
return mPosterPath;
}
public String getTitle() {
return mTitle;
}
public String getReleaseDate() {
return mReleaseDate;
}
public String getOverview() {
return mOverview;
}
public String getVote() {
return mVote +"/10";
}
public void setTrailers(ArrayList<Trailers> trailers) {
this.trailers = trailers;
}
public void setReviews(ArrayList<Reviews> reviews) {
this.reviews = reviews;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mID);
dest.writeString(mTitle);
dest.writeString(mReleaseDate);
dest.writeString(mPosterPath);
dest.writeValue(mBackdrop);
dest.writeString(mVote);
dest.writeString(mOverview);
}
protected Movies(Parcel in) {
mID = in.readLong();
mTitle = in.readString();
mReleaseDate = in.readString();
mPosterPath = in.readString();
mBackdrop = in.readString();
mVote = in.readString();
mOverview = in.readString();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
}
MoviepediaJsonUtils.java where i'm parsing data
public class MoviepediaJsonUtils {
public static ArrayList<Movies> getParseMovieJson(String jsonMovies) throws JSONException {
final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
final String BACKDROP_URL= "https://image.tmdb.org/t/p/w1280/";
JSONObject movieJson = new JSONObject(jsonMovies);
JSONArray movieArray = movieJson.getJSONArray("results");
ArrayList<Movies> movieArrayList = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movieObject = movieArray.getJSONObject(i);
long id = movieObject.getLong("id");
String title = movieObject.getString("title");
String release_date = movieObject.getString("release_date");
String poster_path = movieObject.getString("poster_path");
String backdrop = movieObject.getString("backdrop_path");
String vote_average = movieObject.getString("vote_average");
String overview = movieObject.getString("overview");
Movies movies = new Movies(title, release_date,
IMAGE_BASE_URL + poster_path, BACKDROP_URL+backdrop,vote_average, overview);
movieArrayList.add(movies);
}
return movieArrayList;
}
public static String getResponseFromHttpUrl(InputStream stream) throws IOException {
Scanner scanner = new Scanner(stream);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
}
}
MainActivityFragments.java
public class MainActivityFragments extends Fragment {
private static final int COLUMN = 2;
private RecyclerView mRecyclerView;
SharedPreferences mSettings;
GridLayoutManager mGridLayoutManager;
private SharedPreferences.Editor mEditor;
private static final String SHARED_KEY_SORT = "sort";
private static final String POPULARITY = "popular";
private static final String RATINGS = "top_rated";
public static String[] backdrop;
public static final String SAVE_LAST_UPDATE_ORDER = "save_last_update_order";
private String mLastUpdateOrder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.poster_fragment, container, false);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mGridLayoutManager = new GridLayoutManager(getActivity(),2, LinearLayoutManager.VERTICAL,false);
}else{
mGridLayoutManager = new GridLayoutManager(getActivity(), 4,LinearLayoutManager.VERTICAL,false);
}
mRecyclerView = view.findViewById(R.id.rv_movies);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSettings.edit();
mEditor.apply();
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), new ArrayList<Movies>()));
return view;
}
#Override
public void onStart() {
super.onStart();
if (needToUpdateUi()) {
updateUi();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVE_LAST_UPDATE_ORDER, mLastUpdateOrder);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mLastUpdateOrder = savedInstanceState.getString(SAVE_LAST_UPDATE_ORDER);
}
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
updateUi();
}
// OnCreateOptionMenues will be here
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.poster_fragment, menu);
Drawable drawable = menu.findItem(R.id.icon).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}
}
// OnOptionitemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.poularity:
mEditor.putString(SHARED_KEY_SORT, POPULARITY);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
case R.id.top_rated:
mEditor.putString(SHARED_KEY_SORT, RATINGS);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
if (sortBy.equals(POPULARITY)) {
menu.findItem(R.id.poularity).setChecked(true);
} else {
menu.findItem(R.id.top_rated).setChecked(true);
}
}
private void updateUi() {
if (isNetworkAvailable()) {
OnTaskCompleted taskCompleted = new OnTaskCompleted() {
#Override
public void onFetchMoviesTaskCompleted(ArrayList<Movies> movies) {
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), movies));
}
};
MoviesAsyncTask moviesAsyncTask = new MoviesAsyncTask(taskCompleted);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
mLastUpdateOrder = sortBy;
moviesAsyncTask.execute(sortBy);
} else {
Toast.makeText(this.getActivity().getApplicationContext(), "Need Internet Connection", Toast.LENGTH_LONG).show();
}
}
private boolean needToUpdateUi() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (!mLastUpdateOrder.equals(prefs.getString(SHARED_KEY_SORT, POPULARITY))) {
return true;
} else {
return false;
}
}
//Based on a stackoverflow snippet
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
DeatailActivityFragment
public class DetailActivityFragments extends Fragment {
private final String TAG = this.getClass().getSimpleName();
private static final String PARCEL_KEY = "movie_parcel";
Movies mMovie;
OnTaskCompleted mlistener;
ArrayList<Trailers> mTrailers;
ArrayList<Reviews> mReviews;
ImageView poster;
ImageView backdrop;
public DetailActivityFragments() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_detail_fragment,
container, false);
Movies parceableExtra = getActivity().getIntent().getParcelableExtra(PARCEL_KEY);
poster = view.findViewById(R.id.poster_IV);
TextView title = view.findViewById(R.id.title_TV);
TextView releaseDate = view.findViewById(R.id.relaesedate_TV);
TextView vote = view.findViewById(R.id.vote_TV);
TextView overView = view.findViewById(R.id.overview_TV);
backdrop = view.findViewById(R.id.image_id);
final FloatingActionButton fab1 = view.findViewById(R.id.fab);
//String gotPosition = getStringExtra("position");
//intGotPosition=Integer.parseInt(gotPosition);
// String url = "https://image.tmdb.org/t/p/w1280"+DetailActivityFragments.backdrop[intGotPosition];
title.setText(parceableExtra.getTitle());
releaseDate.setText(parceableExtra.getReleaseDate());
vote.setText(parceableExtra.getVote());
overView.setText(parceableExtra.getOverview());
Picasso.with(view.getContext()).load(parceableExtra.getPosterPath())
.into(poster);
Picasso.with(this.getActivity()).load( parceableExtra.getmBackdrop())
.error(R.drawable.sam).into(backdrop);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent i=new Intent(context , TrailerActivity.class);
startActivity(i);
}
});
return view;
}
}
MoviesAsyncTask.java
public class MoviesAsyncTask extends AsyncTask<String, Void, ArrayList<Movies>> {
private final String LOG_TAG = MoviesAsyncTask.class.getSimpleName();
final String MY_API_KEY = "removed deliberately";
ArrayList<Movies> mMovies;
private OnTaskCompleted mListener;
public MoviesAsyncTask(OnTaskCompleted listener) {
mListener = listener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Movies> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
final String MOVIEDB_BASE_URL =
"https://api.themoviedb.org/3/movie/";
final String APIKEY = "api_key";
Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter(APIKEY, MY_API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String response = null;
try {
response = MoviepediaJsonUtils.getResponseFromHttpUrl(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
return MoviepediaJsonUtils.getParseMovieJson(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Movies> movies) {
super.onPostExecute(movies);
mListener.onFetchMoviesTaskCompleted(movies);
mMovies = movies;
}
}
Try to add your string at the end of your class or remove all the parcelable generated code, add your string, then apply again the parcelable implementation.
This happens because you're not updating the parcel methods.
So am working with retrofit and rxjava for my application.so am using the #GET annociation to pull my blog details from the server that include blog_title, blog_content, blog_thumbnail etc and all this parameter are within an array called blog_post.
I have my APIClient:
public class ApiClient {
private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
private static ApiClient instance;
private ApiService apiService;
private ApiClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
// TODO: 21/03/2017 when going live change the log level to NONE, to enhance performance
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line for logging requests!
final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//final Retrofit retrofit = new Retrofit.Builder().baseUrl(STAGING_BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(STAGING_BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
}
public static ApiClient getInstance(){
if(instance == null){
instance = new ApiClient();
}
return instance;
}
//API CALL FOR LOGIN
public Observable<UserItem> login(String email, String password){
return apiService.signIn(email,password);
}
//API CALL FOR SIGNUP
public Observable<StatusItem> signup(String email, String password, String full_name, String phone){
return apiService.signUp(email, password,phone,full_name);
}
//API CALL FOR BLOG DETAILS
public Observable<BlogResponse> blog_post(){
return apiService.blog_post();
}
}
ApiService:
public interface ApiService {
#FormUrlEncoded
#POST("signin")
Observable<UserItem> signIn(#Field("email") String email, #Field("password") String password);
#FormUrlEncoded
#POST("signup")
Observable<StatusItem> signUp(#Field("full_name")String full_name, #Field("phone") String phone, #Field("email") String email, #Field("password") String password);
#GET("blog")
Observable<BlogResponse> blog_post();
}
pojo classes:
public class BlogItem {
private int thumbNail;
private String title;
private String summary;
public int getThumbNail() {
return thumbNail;
}
public void setThumbNail(#DrawableRes int thumbNail) {
this.thumbNail = thumbNail;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
public class BlogResponse {
private BlogItem[] blogItems;
public BlogItem[] getBlogItems() {
return blogItems;
}
public void setBlogItems(BlogItem[] blogItems) {
this.blogItems = blogItems;
}
}
I have a recyclerview that will hold all the information that will be coming from the server. But the problem is that when I run it I get a log response in my RUN terminal but nothing is showing on the app screen.
this is my FragmentClass that holds the information from the server:
BlogFragment:
public class BlogFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private RecyclerView recyclerView;
private BlogAdapter adapter;
private List<BlogItem> blogItems;
private View view;
public BlogFragment() {
// Required empty public constructor
}
public static BlogFragment newInstance(String param1) {
BlogFragment fragment = new BlogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_blog, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (RecyclerView) view.findViewById(R.id.blog_posts_list);
setUpViews();
}
private void setUpViews() {
blogItems = new ArrayList<>();
adapter = new BlogAdapter(blogItems);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
BlogPost();
// populateLists();
}
private void BlogPost() {
ApiClient.getInstance().blog_post().observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread()).subscribe(new DisposableObserver<BlogResponse>() {
#Override
public void onNext(BlogResponse value) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(blogItem.getTitle().toString());
blogItem.setSummary(blogItem.getSummary().toString());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
}
});
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
/*
private void populateLists() {
int dummyPostArraySize = 10;
for (int i = 0; i < dummyPostArraySize; i++) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("Post title " + i+1);
blogItem.setThumbNail(isEven(i) ? R.drawable.profile_image : 0);
blogItem.setSummary(getString(isEven(i) ? R.string.summary2 : R.string.summary1));
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}*/
private boolean isEven(int position) {
return (position & 1) == 0;
}
}
Adapter class
public class BlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
private List<BlogItem> blogItems;
public BlogAdapter(List<BlogItem> blogItems) {
this.blogItems = blogItems;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_post_item,
parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
BlogItem blogItem = blogItems.get(position);
holder.bindModel(blogItem);
}
#Override
public int getItemCount() {
return blogItems == null ? (0) : blogItems.size();
}
}
View Holder class
public class BlogViewHolder extends RecyclerView.ViewHolder {
private ImageView cover;
private TextView title;
private TextView summary;
public BlogViewHolder(View itemView) {
super(itemView);
cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
title = (TextView) itemView.findViewById(R.id.post_title);
summary = (TextView) itemView.findViewById(R.id.post_summary);
}
public void bindModel(BlogItem blogItem) {
if (blogItem.getThumbNail() == 0) {
cover.setVisibility(View.GONE);
} else {
cover.setImageResource(blogItem.getThumbNail());
}
title.setText(Html.fromHtml(blogItem.getTitle()));
summary.setText(blogItem.getSummary());
}
}
What am I not doing right. Someone Please Help!!!
In the private void BlogPost() { method, you create BlogItems but then don't do anything with it. You probably forgot to add them to the blogItems list.
In addition, the call to adapter.notifyItemRangeChanged in that method happens way before the sequence receives data but you don't call that after each blogItem or when all blog items have arrived - the observer is on a complete different execution path than the outer BlogPost() method.
Edit spelled out:
#Override
public void onNext(BlogResponse value) {
for (BlogItem responseItem : value.getBlogItems()) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(responseItem.getTitle().toString());
blogItem.setSummary(responseItem.getSummary().toString());
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
blogItems.add(blogItem);
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}