Related
I am trying to implement a dynamic list update to FragmentStatePagerAdapter. I have a list of few fragments which have radio buttons, edit text, and different other fragments having just a single view.
Now the logic revolves around radio button fragment, so lets suppose you have a list having 10 elements and the list item showing the radio button is 6, and there are 2 options for the user to select on the radio button fragment. If user selects 1st option then 8th item should be shown and 7th should be skipped and if 2nd option is selected then 7th should be shown and then 9th.
I have added a view pager, and have an associated FragmentStatePagerAdapter associated with it. Now I was able to populate the list based on the option but when I refresh list in the adapter, it does not hops from 6th to 8th and still shows 7th.
Can someone help me around it on how can I implement the hopping mechanism on FragmentStatePagerAdapter?
Adapter
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import java.util.List;
public class OrderDetailsAdapter extends FragmentPagerAdapter {
private final Logger log = LoggerFactory.getLogger(OrderDetailsAdapter.class);
private List<IndexedFragments> adapterList;
private FragmentManager fragmentManager;
public OrderDetailsAdapter(FragmentManager fragmentManager, List<IndexedFragments> adapterList) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
this.adapterList = adapterList;
}
#Override
public Fragment getItem(int position) {
final IndexedFragments indexedFragment = adapterList.get(position);
return indexedFragment.getFragment();
}
#Override
public int getCount() {
if (adapterList.isEmpty()) {
return 0;
} else {
return adapterList.size();
}
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
log.debug("Destroying fragment position {}", position);
}
public void updateList(List<IndexedFragments> indexedFragments) {
adapterList.clear();
log.debug("Fragment List OrderDetailsAdapter after clearing {} on {}", adapterList.size(), adapterList);
adapterList.addAll(indexedFragments);
log.debug("Fragment List OrderDetailsAdapter after adding indexed fragments {} on {}", adapterList.size(), adapterList);
notifyDataSetChanged();
}
}
Model Class
import android.support.v4.app.Fragment;
import java.io.Serializable;
public class IndexedFragments implements Serializable {
private final static long serialVersionUID = -304520750038118996L;
private Integer index;
private Fragment fragment;
private boolean isSkippedRequested = false;
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Fragment getFragment() {
return fragment;
}
public void setFragment(Fragment fragment) {
this.fragment = fragment;
}
public boolean isSkippedRequested() {
return isSkippedRequested;
}
public void setSkippedRequested(boolean skippedRequested) {
isSkippedRequested = skippedRequested;
}
}
FormsActivity
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.inject.Inject;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
public class FormsActivity extends AppCompatActivity implements FragmentNavigationListener {
private static String CHECK_BOX = "checkbox";
private static String RADIO_BUTTON = "radio";
private static String TEXT_INPUT = "text";
private static String NUMERIC_INPUT = "numeric";
private static String VIDEO_VIEW = "video";
private static String IMAGE_VIEW = "image";
private final Logger log = LoggerFactory.getLogger(FormsActivity.class);
public LinkedHashMap<String, String> stringLinkedHashMap;
#Inject
protected BaseRetrofit restRequests;
#Inject
protected AppUtils appUtils;
private FormData formData;
private ViewPager viewPager;
private ProgressBar progressBar;
private Button submitButton;
private Toolbar toolbar;
private List<Frmdtl> formDataList;
private List<IndexedFragments> fragmentList;
private Context context;
private OrderDetailsAdapter orderDetailsAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forms);
context = this;
Intent intent = getIntent();
if (intent != null) {
formData = (FormData) intent.getSerializableExtra(AppConstants.FORMS_ACTIVITY);
}
restRequests.setContext(this);
initializeViews();
populateFragments(formData);
}
#Override
public void onBackPressed() {
showAlertDialog();
}
private void initializeViews() {
submitButton = findViewById(R.id.submit_button);
toolbar = findViewById(R.id.toolbar_main_activity);
setSupportActionBar(toolbar);
progressBar = findViewById(R.id.progress_bar_layout);
}
private void showAlertDialog() {
Dialog dialog = new AlertDialogFragment().createWarningDialog(context, getString(R.string.warning),
getString(R.string.saved_form_data_lost),
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
appUtils.getFormAnswersList().clear();
finish();
}
});
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
#SuppressLint("ClickableViewAccessibility")
private void populateFragments(FormData formData) {
formDataList = formData.getOrderDetails().getFrmdtl();
fragmentList = new ArrayList<>();
for (Frmdtl frmdtl : formDataList) {
Fragment fragment = null;
if (frmdtl.getFieldType().equalsIgnoreCase(TEXT_INPUT)) {
fragment = createTextFieldFragment(frmdtl, null);
} else if (frmdtl.getFieldType().equalsIgnoreCase(NUMERIC_INPUT)) {
fragment = createTextFieldFragment(frmdtl, NUMERIC_TYPE);
} else if (frmdtl.getFieldType().equalsIgnoreCase(CHECK_BOX)) {
fragment = createCheckBoxFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(RADIO_BUTTON)) {
fragment = createRadioButtonFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(VIDEO_VIEW)) {
fragment = createVideoViewFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(IMAGE_VIEW)) {
fragment = createImageViewFragment(frmdtl);
}
if (fragment != null) {
IndexedFragments indexedFragments = new IndexedFragments();
indexedFragments.setFragment(fragment);
indexedFragments.setIndex(frmdtl.getIndex());
fragmentList.add(indexedFragments);
}
}
viewPager = findViewById(R.id.fragment_view_pager);
orderDetailsAdapter = new OrderDetailsAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(orderDetailsAdapter);
viewPager.setOffscreenPageLimit(0);
}
private Fragment createTextFieldFragment(Frmdtl formData, String inputType) {
FormEditTextFragment formEditTextFragment = new FormEditTextFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
bundle.putString(INPUT_TYPE, inputType);
formEditTextFragment.setArguments(bundle);
log.debug("Form Data Id for text {}", formData.getId());
return formEditTextFragment;
}
private Fragment createCheckBoxFragment(Frmdtl formData) {
FormCheckBoxFragment formCheckBoxFragment = new FormCheckBoxFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formCheckBoxFragment.setArguments(bundle);
log.debug("Form Data Id for check {}", formData.getId());
return formCheckBoxFragment;
}
private Fragment createRadioButtonFragment(Frmdtl frmdtl) {
FormRadioButtonFragment formRadioButtonFragment = new FormRadioButtonFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, frmdtl);
bundle.putSerializable(ORDER_DETAILS, formData.getOrderDetails());
formRadioButtonFragment.setArguments(bundle);
log.debug("Form Data Id for radio {}", frmdtl.getId());
return formRadioButtonFragment;
}
private Fragment createVideoViewFragment(Frmdtl formData) {
FormVideoFragment formVideoFragment = new FormVideoFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formVideoFragment.setArguments(bundle);
log.debug("Form Data Id for video {}", formData.getId());
return formVideoFragment;
}
private Fragment createImageViewFragment(Frmdtl formData) {
FormImageFragment formImageFragment = new FormImageFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formImageFragment.setArguments(bundle);
log.debug("Form Data Id for image {}", formData.getId());
return formImageFragment;
}
private void navigateBetweenFragments(int navigation, List<String> stringList, Integer currentIndex) {
if (navigation == NEXT_NAVIGATION) {
if (stringList != null && !stringList.isEmpty() && currentIndex != null) {
processLogicBasedFragments(stringList, currentIndex);
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
return;
}
if (viewPager.getCurrentItem() == fragmentList.size() - 1) {
log.debug("FormData list size {}", formDataList.size());
log.debug("Moving to {} form", viewPager.getCurrentItem() + 1);
submitButton.setVisibility(View.VISIBLE);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
attemptFormUpload();
}
});
} else {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
}
if (navigation == PREVIOUS_NAVIGATION) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
private void processLogicBasedFragments(List<String> stringList, Integer currentIndex) {
List<IndexedFragments> indexedFragmentsList = new ArrayList<>();
for (int i = 0; i < fragmentList.size(); i++) {
Integer index = fragmentList.get(i).getIndex();
if (index.compareTo(currentIndex) <= 0) {
indexedFragmentsList.add(fragmentList.get(i));
}
}
for (int i = 0; i < fragmentList.size(); i++) {
IndexedFragments indexedFragments = fragmentList.get(i);
if (stringList.contains(String.valueOf(indexedFragments.getIndex()))) {
indexedFragmentsList.add(indexedFragments);
} else if (!stringList.contains(String.valueOf(indexedFragments.getIndex()))
&& fragmentList.get(i).getIndex().compareTo(currentIndex) > 0) {
indexedFragments.setSkippedRequested(true);
indexedFragmentsList.add(indexedFragments);
}
}
fragmentList.clear();
log.debug("Fragment List Forms Activity after clearing {} on {}", fragmentList.size(), fragmentList);
fragmentList.addAll(indexedFragmentsList);
log.debug("Fragment List Forms Activity after adding indexed fragments {} on {}", fragmentList.size(), fragmentList);
orderDetailsAdapter.updateList(indexedFragmentsList);
}
private void attemptFormUpload() {
try {
if (appUtils.isNetworkConnected(context)) {
uploadForm();
} else {
preserveFormDataForFutureUpload();
Toast.makeText(context, R.string.no_connection, Toast.LENGTH_LONG).show();
progressBar.setVisibility(GONE);
finish();
}
} catch (IOException e) {
log.error("Error in attempting to upload form {}", e.fillInStackTrace());
}
}
private void uploadForm() throws UnsupportedEncodingException {
restRequests.uploadForm(formData.getOrderDetails().getId(),
String.valueOf(formData.getOrderDetails().getFormId()),
formData.getOrderDetails().getLatitude(),
formData.getOrderDetails().getLongitude(),
appUtils.getFormAnswersList(), new RestRequestListener() {
#Override
public void onSuccessResponse(String response) {
appUtils.getFormAnswersList().clear();
progressBar.setVisibility(GONE);
finish();
}
#Override
public void onErrorResponse(Throwable t) {
appUtils.getFormAnswersList().clear();
progressBar.setVisibility(GONE);
finish();
}
});
}
private void preserveFormDataForFutureUpload() throws IOException {
OfflineSubmittedOrder offlineSubmittedOrder = new OfflineSubmittedOrder();
List<FormAnswers> formAnswers = new ArrayList<>(appUtils.getFormAnswersList());
offlineSubmittedOrder.setFormAnswersList(formAnswers);
offlineSubmittedOrder.setOrderDetail(formData.getOrderDetails());
appUtils.getFormAnswersList().clear();
appUtils.getOfflineSubmittedOrders().add(offlineSubmittedOrder);
appUtils.writeObject(getApplicationContext(), FORM_ANSWER_LIST_CACHE, appUtils.getOfflineSubmittedOrders());
appUtils.setSubmissionPending(true);
}
#Override
public void onFragmentNavigationTriggered(int navigation, List<String> stringList, Integer currentIndex) {
navigateBetweenFragments(navigation, stringList, currentIndex);
}
#Subcomponent
public interface FormsActivitySubcomponent extends AndroidInjector<FormsActivity> {
#SuppressWarnings({"InnerClassTooDeeplyNested", "ClassNameSameAsAncestorName"})
#Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<FormsActivity> {
}
}
#SuppressWarnings("InterfaceNeverImplemented")
#Module(subcomponents = FormsActivity.FormsActivitySubcomponent.class)
public interface FormsActivityModule {
#Binds
#IntoMap
#ActivityKey(FormsActivity.class)
AndroidInjector.Factory<? extends Activity>
bindFormsActivityInjectorFactory(FormsActivity.FormsActivitySubcomponent.Builder builder);
}
}
here is my code for SelectedCategoryActivity.java
its showing error that ArrayList cannot be cast to com.panaceasoft.citiesdirectory.models.PCityData, while I used the same way in my other code
package com.panaceasoft.citiesdirectory.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.panaceasoft.citiesdirectory.Config;
import com.panaceasoft.citiesdirectory.GlobalData;
import com.panaceasoft.citiesdirectory.R;
import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter;
//import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter1;
//import com.panaceasoft.citiesdirectory.models.CategoryRowData;
import com.panaceasoft.citiesdirectory.adapters.CityAdapter;
import com.panaceasoft.citiesdirectory.listeners.ClickListener;
import com.panaceasoft.citiesdirectory.listeners.RecyclerTouchListener;
import com.panaceasoft.citiesdirectory.models.CategoryData;
import com.panaceasoft.citiesdirectory.models.CityRowData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;
import com.panaceasoft.citiesdirectory.models.PSubCategoryData;
import com.panaceasoft.citiesdirectory.utilities.Utils;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dell on 04-Jul-16.
*/
public class SelectedCategoryActivity extends AppCompatActivity {
private ProgressDialog prgDialog;
private String jsonStatusSuccessString;
private CollapsingToolbarLayout collapsingToolbar;
private Toolbar toolbar;
private ImageView detailImage;
private TextView txtTitle;
private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mLayoutManager;
private CityAdapter mAdapter;
private List<PCityData> myDataset = new ArrayList<>();
private CityRowData info;
private int selectedCategoryID;
private int selectedCityID;
private CategoryData category;
private PCityData city;
private ArrayList<PCityData> cityArrayList ;
//private ArrayList<PCityData> cityArrayData ;
private ArrayList<PSubCategoryData> subCategoryArrayList ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_category);
initUI();
initData();
saveSelectedCategoryInfo(category);
bindData();
loadCityGrid();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_news, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_news) {
Utils.psLog("Open News Activity");
final Intent intent;
intent = new Intent(this, NewsListActivity.class);
intent.putExtra("selected_category_id", selectedCategoryID + "");
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.blank_anim, R.anim.left_to_right);
}
private void initUI() {
initToolbar();
initCollapsingToolbarLayout();
}
private void initCollapsingToolbarLayout(){
try {
collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
} catch (Exception e) {
Utils.psErrorLogE("Error in initCollapsingToolbarLayout.", e);
}
}
private void initToolbar() {
try {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(Utils.isAndroid_5_0()){
Utils.setMargins(toolbar, 0, -102, 0, 0);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitle("");
toolbar.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
} catch (Resources.NotFoundException e) {
Utils.psErrorLogE("Error in initToolbar.", e);
}
}
private void initData() {
try {
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
requestData(Config.APP_API_URL + Config.GET_ALL);
detailImage = (ImageView) findViewById(R.id.detail_image);
category = GlobalData.categorydata;
//city = GlobalData.citydata;
selectedCategoryID = category.id;
//selectedCityID = city.id;
} catch (Exception e) {
Utils.psErrorLogE("Error in initData.", e);
}
}
private void bindData() {
try {
if(collapsingToolbar != null){
collapsingToolbar.setTitle(Utils.getSpannableString(category.name));
makeCollapsingToolbarLayoutLooksGood(collapsingToolbar);
}
Picasso.with(getApplicationContext()).load(Config.APP_IMAGES_URL + category.cover_image_file).into(detailImage);
} catch (Exception e) {
Utils.psErrorLogE("Error in bindData.", e);
}
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
Utils.psLog("City Status >>>>>>>>>>>>>: " + status);
if (status.equals(jsonStatusSuccessString)) {
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
//cityArrayList = gson.fromJson(response.getString("data"), listType);
Utils.psLog("City Count >>>>>>>>>>>>>: " + cityArrayList.size());
updateGlobalCityList();
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading City List.", e);
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
prgDialog.cancel();
Utils.psLog("Error: " + error.getMessage());
}
// #Override
});
RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
queue.add(request);
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : cityArrayList) {
GlobalData.cityDatas.add(cd);
}
}
public void loadCityGrid() {
try {
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CityAdapter(myDataset, mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
//cityArrayList = category.cities;
// for (PCityData cd : cityArrayList) {
// subCategoryArrayList = cd.sub_categories;
// info = new CityRowData();
//info.setCityId(cd.id);
// info.setCityName(cd.name);
//info.setCityImage(cd.cover_image_file);
// myDataset.add(info);
// }
mAdapter.notifyItemInserted(myDataset.size());
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
mRecyclerView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
} catch (Resources.NotFoundException e) {
Utils.psErrorLogE("Error in loadCityGrid.", e);
}
}
public void onItemClicked( int position){
final Intent intent;
intent = new Intent(this,SubCategoryActivity.class);
GlobalData.citydata = cityArrayList.get(position);
intent.putExtra("selected_city_index", position );
intent.putExtra("selected_category_id", selectedCategoryID);
intent.putExtra("selected_city_id", cityArrayList.get(0).id);
startActivity(intent);
overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void makeCollapsingToolbarLayoutLooksGood(CollapsingToolbarLayout collapsingToolbarLayout) {
try {
final Field field = collapsingToolbarLayout.getClass().getDeclaredField("mCollapsingTextHelper");
field.setAccessible(true);
final Object object = field.get(collapsingToolbarLayout);
final Field tpf = object.getClass().getDeclaredField("mTextPaint");
tpf.setAccessible(true);
((TextPaint) tpf.get(object)).setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
((TextPaint) tpf.get(object)).setColor(getResources().getColor(R.color.colorAccent));
} catch (Exception ignored) {
}
}
private void saveSelectedCategoryInfo(CategoryData ct) {
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("_id", ct.id);
editor.putString("_name", ct.name);
editor.putString("_cover_image", ct.cover_image_file);
// editor.putString("_address", ct.address);
// editor.putString("_city_region_lat", ct.lat);
// editor.putString("_city_region_lng", ct.lng);
editor.commit();
} catch (Exception e) {
Utils.psErrorLogE("Error in saveSelectedCategoryInfo.", e);
}
}
}
GlobalData.java
package com.panaceasoft.citiesdirectory;
import com.panaceasoft.citiesdirectory.models.CategoryData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;
import java.util.ArrayList;
public class GlobalData {
public static PItemData itemData = null;
public static PCityData citydata = null;
public static CategoryData categorydata = null;
public static ArrayList<PCityData> cityDatas = new ArrayList<PCityData>();
public static ArrayList<CategoryData> categoryDatas = new ArrayList<CategoryData>();
}
PCityData.java
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
// public ArrayList<PSubCategoryData> sub_categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
// if (in.readByte() == 0x01) {
// sub_categories = new ArrayList<PSubCategoryData>();
// in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
// } else {
// sub_categories = null;
// }
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
//if (sub_categories == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeList(sub_categories);
// }
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
logcat
07-12 02:58:33.320 1797-1797/com.panaceasoft.citiesdirectory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 1797
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.panaceasoft.citiesdirectory.models.PCityData
at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:209)
at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:199)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I think the below line contains error
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
I think you are trying to cast gson.fromJson(response.getString("data"), listType) to PCityData which is ArrayList
you are getting error on this line:
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
because:
gson.fromJson(response.getString("data"), listType);
this return a arraylist and it is not casting into your custom model
to fix this change your GlobalData.java class
public static PCityData citydata = null;
to
public static ArrayList<PCityData> citydata = null;
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
// Issue is here
GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
Fix 1 : GlobalData.citydata should be of type List<PCityData>.
Fix 2 : Change like this GlobalData.citydata = (List<PCityData>) gson.fromJson(response.getString("data"), listType);
I try to solve using below code:
[Reference: Android: Clear Cache of All Apps?
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
and add permission in AndroidMenifest.xml file
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
But when i run this code, then throw exception :
java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2
Any suggestion to overcome this exception or another solution for clear cache of all apps programmatically. Thanks
follow the link. hopefully get a solutions
https://fossdroid.com/s.html?q=cache+cleaner
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.frozendevs.cache.cleaner.R;
import com.frozendevs.cache.cleaner.activity.SettingsActivity;
import com.frozendevs.cache.cleaner.model.AppsListItem;
import com.frozendevs.cache.cleaner.model.CleanerService;
import com.frozendevs.cache.cleaner.model.adapter.AppsListAdapter;
import com.frozendevs.cache.cleaner.widget.DividerDecoration;
import com.frozendevs.cache.cleaner.widget.RecyclerView;
import java.util.List;
public class CleanerFragment extends Fragment implements CleanerService.OnActionListener {
private static final int REQUEST_STORAGE = 0;
private static final String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private CleanerService mCleanerService;
private AppsListAdapter mAppsListAdapter;
private TextView mEmptyView;
private SharedPreferences mSharedPreferences;
private ProgressDialog mProgressDialog;
private View mProgressBar;
private TextView mProgressBarText;
private LinearLayoutManager mLayoutManager;
private Menu mOptionsMenu;
private boolean mAlreadyScanned = false;
private boolean mAlreadyCleaned = false;
private String mSearchQuery;
private String mSortByKey;
private String mCleanOnAppStartupKey;
private String mExitAfterCleanKey;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mCleanerService = ((CleanerService.CleanerServiceBinder) service).getService();
mCleanerService.setOnActionListener(CleanerFragment.this);
updateStorageUsage();
if (!mCleanerService.isCleaning() && !mCleanerService.isScanning()) {
if (mSharedPreferences.getBoolean(mCleanOnAppStartupKey, false) &&
!mAlreadyCleaned) {
mAlreadyCleaned = true;
cleanCache();
} else if (!mAlreadyScanned) {
mCleanerService.scanCache();
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mCleanerService.setOnActionListener(null);
mCleanerService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
mSortByKey = getString(R.string.sort_by_key);
mCleanOnAppStartupKey = getString(R.string.clean_on_app_startup_key);
mExitAfterCleanKey = getString(R.string.exit_after_clean_key);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mAppsListAdapter = new AppsListAdapter();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.cleaning_cache);
mProgressDialog.setMessage(getString(R.string.cleaning_in_progress));
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
getActivity().getApplication().bindService(new Intent(getActivity(), CleanerService.class),
mServiceConnection, Context.BIND_AUTO_CREATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleaner_fragment, container, false);
mEmptyView = (TextView) rootView.findViewById(R.id.empty_view);
mLayoutManager = new LinearLayoutManager(getActivity());
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAppsListAdapter);
recyclerView.setEmptyView(mEmptyView);
recyclerView.addItemDecoration(new DividerDecoration(getActivity()));
mProgressBar = rootView.findViewById(R.id.progressBar);
mProgressBarText = (TextView) rootView.findViewById(R.id.progressBarText);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
mOptionsMenu = menu;
inflater.inflate(R.menu.main_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mSearchQuery = query;
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (ViewCompat.isLaidOut(searchView) && mSearchQuery != null) {
String oldText = mSearchQuery;
mSearchQuery = newText;
if (!oldText.equals(newText)) {
mAppsListAdapter.sortAndFilter(getActivity(), getSortBy(), newText);
}
}
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
if (mSearchQuery == null) {
mSearchQuery = "";
}
mAppsListAdapter.setShowHeaderView(false);
mEmptyView.setText(R.string.no_such_app);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mSearchQuery = null;
mAppsListAdapter.clearFilter();
mAppsListAdapter.setShowHeaderView(true);
if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
mLayoutManager.scrollToPosition(0);
}
mEmptyView.setText(R.string.empty_cache);
return true;
}
});
if (mSearchQuery != null) {
MenuItemCompat.expandActionView(searchItem);
searchView.setQuery(mSearchQuery, false);
}
updateOptionsMenu();
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clean:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning() && mCleanerService.getCacheSize() > 0) {
mAlreadyCleaned = false;
cleanCache();
}
return true;
case R.id.action_refresh:
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mCleanerService.scanCache();
}
return true;
case R.id.action_settings:
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
case R.id.action_sort_by_app_name:
setSortBy(AppsListAdapter.SortBy.APP_NAME);
updateOptionsMenu();
return true;
case R.id.action_sort_by_cache_size:
setSortBy(AppsListAdapter.SortBy.CACHE_SIZE);
updateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
updateOptionsMenu();
}
#Override
public void onDestroyOptionsMenu() {
mOptionsMenu = null;
}
#Override
public void onResume() {
updateStorageUsage();
updateOptionsMenu();
if (mCleanerService != null) {
if (mCleanerService.isScanning() && !isProgressBarVisible()) {
showProgressBar(true);
} else if (!mCleanerService.isScanning() && isProgressBarVisible()) {
showProgressBar(false);
}
if (mCleanerService.isCleaning() && !mProgressDialog.isShowing()) {
mProgressDialog.show();
}
}
super.onResume();
}
#Override
public void onPause() {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
super.onPause();
}
#Override
public void onDestroy() {
getActivity().getApplication().unbindService(mServiceConnection);
super.onDestroy();
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
mOptionsMenu.findItem(R.id.action_sort_by_app_name).setVisible(
getSortBy() == AppsListAdapter.SortBy.CACHE_SIZE);
mOptionsMenu.findItem(R.id.action_sort_by_cache_size).setVisible(
getSortBy() == AppsListAdapter.SortBy.APP_NAME);
}
}
private void updateStorageUsage() {
if (mAppsListAdapter != null) {
StatFs stat = new StatFs(Environment.getDataDirectory().getAbsolutePath());
long totalMemory = (long) stat.getBlockCount() * (long) stat.getBlockSize();
long medMemory = mCleanerService != null ? mCleanerService.getCacheSize() : 0;
long lowMemory = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
!Environment.isExternalStorageEmulated()) {
stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
totalMemory += (long) stat.getBlockCount() * (long) stat.getBlockSize();
lowMemory += (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
long highMemory = totalMemory - medMemory - lowMemory;
mAppsListAdapter.updateStorageUsage(totalMemory, lowMemory, medMemory, highMemory);
}
}
private AppsListAdapter.SortBy getSortBy() {
try {
return AppsListAdapter.SortBy.valueOf(mSharedPreferences.getString(mSortByKey,
AppsListAdapter.SortBy.CACHE_SIZE.toString()));
} catch (ClassCastException e) {
return AppsListAdapter.SortBy.CACHE_SIZE;
}
}
private void setSortBy(AppsListAdapter.SortBy sortBy) {
mSharedPreferences.edit().putString(mSortByKey, sortBy.toString()).apply();
if (mCleanerService != null && !mCleanerService.isScanning() &&
!mCleanerService.isCleaning()) {
mAppsListAdapter.sortAndFilter(getActivity(), sortBy, mSearchQuery);
}
}
private boolean isProgressBarVisible() {
return mProgressBar.getVisibility() == View.VISIBLE;
}
private void showProgressBar(boolean show) {
if (show) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.startAnimation(AnimationUtils.loadAnimation(
getActivity(), android.R.anim.fade_out));
mProgressBar.setVisibility(View.GONE);
}
}
private void showStorageRationale() {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setTitle(R.string.rationale_title);
dialog.setMessage(getString(R.string.rationale_storage));
dialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private void cleanCache() {
if (!CleanerService.canCleanExternalCache(getActivity())) {
if (shouldShowRequestPermissionRationale(PERMISSIONS_STORAGE[0])) {
showStorageRationale();
} else {
requestPermissions(PERMISSIONS_STORAGE, REQUEST_STORAGE);
}
} else {
mCleanerService.cleanCache();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCleanerService.cleanCache();
} else {
showStorageRationale();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onScanStarted(Context context) {
if (isAdded()) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mProgressBarText.setText(R.string.scanning);
showProgressBar(true);
}
}
#Override
public void onScanProgressUpdated(Context context, int current, int max) {
if (isAdded()) {
mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
}
}
#Override
public void onScanCompleted(Context context, List<AppsListItem> apps) {
mAppsListAdapter.setItems(getActivity(), apps, getSortBy(), mSearchQuery);
if (isAdded()) {
updateStorageUsage();
showProgressBar(false);
}
mAlreadyScanned = true;
}
#Override
public void onCleanStarted(Context context) {
if (isAdded()) {
if (isProgressBarVisible()) {
showProgressBar(false);
}
if (!getActivity().isFinishing()) {
mProgressDialog.show();
}
}
}
#Override
public void onCleanCompleted(Context context, boolean succeeded) {
if (succeeded) {
mAppsListAdapter.trashItems();
}
if (isAdded()) {
updateStorageUsage();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Toast.makeText(context, succeeded ? R.string.cleaned : R.string.toast_could_not_clean,
Toast.LENGTH_LONG).show();
if (succeeded && getActivity() != null && !mAlreadyCleaned &&
mSharedPreferences.getBoolean(mExitAfterCleanKey, false)) {
getActivity().finish();
}
}
}
It looks like there is an additional freeStorage() method added in Android 6 (Marshmallow) that takes an additional volumeUuid parameter:
public void freeStorage(long freeStorageSize, IntentSender pi)
public abstract void freeStorage(String volumeUuid, long freeStorageSize,
IntentSender pi)
Obviously, the new method is showing up first in the returned list of declared methods.
To get around this, you can alter the orginal code so that it looks like this:
PackageManager pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
Class[] params = m.getParameterTypes();
if (params.length == 2) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}
}
I need to pass an arraylist which contains object with a string and arraylist. I am unable to pass the arraylist to other activity. In the Activity1 the list contains value that I have verified.
DepositBn:
package support;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class DepositBn implements Parcelable {
private String limit;
#SerializedName("period")
private ArrayList<Rate> rateList;
protected DepositBn(Parcel in) {
limit = in.readString();
}
public String getLimit() {
return limit;
}
public void setLimit(String limit) {
this.limit = limit;
}
public ArrayList<Rate> getRateList() {
return rateList;
}
public void setRateList(ArrayList<Rate> rateList) {
this.rateList = rateList;
}
public class Rate {
private String rate;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(limit);
}
public static final Creator<DepositBn> CREATOR = new Creator<DepositBn>() {
#Override
public DepositBn createFromParcel(Parcel in) {
return new DepositBn(in);
}
#Override
public DepositBn[] newArray(int size) {
return new DepositBn[size];
}
};
}
In the Activity1:
#Override
protected void onPostExecute(ArrayList<DepositBn> result) {
super.onPostExecute(result);
System.out.println("result = " + result);
for (DepositBn depositBn : result) {
System.out.println("----" + depositBn.getLimit());
}
try {
Intent intent = new Intent(DepositRates.this, GenericRateDisplay.class);
Resources res = DepositRates.this.getResources();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("depositBnArrayList",result);
bundle.putString("pageName", res.getString(R.string.domesticRates));
intent.putExtras(bundle);
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
In Activity2:
package in.co.sbm.sbmvirtual;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import support.DepositBn;
public class GenericRateDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generic_rate_display);
Bundle b = this.getIntent().getExtras();
ArrayList<DepositBn> depositBnArrayList = b.getParcelableArrayList("depositBnArrayList");
//String pageName = b.getString("pageName");
ArrayList<String> rateList = new ArrayList();
for (DepositBn depositBn : depositBnArrayList) {
for(DepositBn.Rate rate : depositBn.getRateList()){
rateList.add(rate.toString());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericRateDisplay.this,
android.R.layout.simple_list_item_1, rateList);
ListView listView = (ListView) findViewById(R.id.genericListView);
listView.setAdapter(adapter);
}
}
I have fixed it. I have used inner class as well which I did not serialize hence I was unable to use putSerializable. I have serialized both the outer and inner class and used intent.putSerializable.
Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks