Illegalstateexception content view not yet created in listfragment - android

The problem is, when I make a search into the listfragment, it works. When I close it and open again and do another search, the exception appears. In the developers options I choose to not maintain the activities.
I guess the references of the layout are lost when the app wakes up, but have no idea why.
What can I do?
This is my code
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listAdapter = new ListAdapter(getActivity(), adArrayList);
setListAdapter(listAdapter);
getListView().setOnScrollListener(this);
}
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
ViewGroup viewGroup = (ViewGroup) view;
mPullToRefreshLayout = new PullToRefreshLayout(viewGroup.getContext());
ActionBarPullToRefresh.from(getActivity())
.insertLayoutInto(viewGroup)
.theseChildrenArePullable(android.R.id.list)
.listener(this)
.setup(mPullToRefreshLayout);
}
#Override
public void onResume() {
pagination = 0;
getAds("");
super.onResume() ;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
listView = (ListView) view.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) listView.getParent();
// Remove ListView and add CustomView in its place
int listViewIndex = parent.indexOfChild(listView);
parent.removeViewAt(listViewIndex);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(
R.layout.list_frag, container, false);
parent.addView(linearLayout , listViewIndex,
listView.getLayoutParams());
listView.setDrawSelectorOnTop(false);
listView.setDivider(null);
listView.setDividerHeight(0);
return view;
}
And this is the method I use to get the data from the server
//the next method use retrofit
public void getAds(String productSearch){
isLoadingMoreAds = true;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mPullToRefreshLayout.setRefreshing(true);
} else{
setListShown(false);
}
Services services= Utils.getRESTAdapter();
services.getSearch(new Callback<AdsList>() {
#Override
public void success(AdsList adsList, Response response) {
try{
setListShown(true);
mPullToRefreshLayout.setRefreshComplete();
updateView(adsList.getAd());
isLoadingMoreAds = false;
}catch(IllegalStateException e){
Log.e("Exception", "ListFragment ya no existe");
}
}
#Override
public void failure(RetrofitError error) {
isLoadingMoreAds = false;
mPullToRefreshLayout.setRefreshComplete();
updateView(new ArrayList<Ad>());
setListShown(true);
Log.e("Error", "Failure at get ads");
}
});
}

Related

how to pass list view data to another list view?

I have two Fragment,
I want to send the list view data from fragment 1 to fragment two.
when the user clicks the button on Fragment1_listview.xml the fragment2_listview will appear and it has the same data from fragment1.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
CartFragment();
FragmentManager manager = getSupportFragmentManager();
final int commit =
manager.beginTransaction().replace(R.id.fragment_container, cartFragment,
cartFragment.getTag()).commit();
}
}
Fragment1.java
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_cart, container, false);
return view;
}
#Override
public void processFinish(String s) {
try {
itemList = new JsonConverter<Cart>().toArrayList(s, Cart.class);
} catch (Exception e) {
e.printStackTrace();
}
BindDictionary dic = new BindDictionary();
dic.addStringField(R.id.tvName, new StringExtractor<Cart>() {
#Override
public String getStringValue(Cart item, int position) {
return item.orderName;
}
});
dic.addStringField(R.id.tvDesc, new StringExtractor<Cart>() {
#Override
public String getStringValue(Cart item, int position) {
return item.description;
}
}).visibilityIfNull(View.GONE);
adapter = new FunDapter<>(CartFragment.this.getActivity(), itemList,
R.layout.cart_row, dic);
lv = (ListView)view.findViewById(R.id.lvCart);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
Fragment2.java
public View onCreateView(LayoutInflater inflater, final ViewGroup
container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_payment, container, false);
return view;
}
but I don't know how to do it. please help me.
I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.

SetText EditText not working in Fragment using OnStart, OnResume and onCreateView

I am using Fragment and due to some reasons, EditText is not displaying the data retrieved from a POST request which gives JSON response.
There is no issue in JSON response. I also used OnResume and OnStart methods but still nothing working.
Am I missing anthing?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
InitializeControls(fragment_profile);
NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
#Override
public void getResult(JOM_User object) {
user = object.getUser();
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
}
});
return inflater.inflate(R.layout.fragment_profile, container, false);
}
#Override
public void OnStart() {
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
return super.OnStart();
}
#Override
public void OnResume() {
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
return super.OnStart();
}
Try initialising txtEmailAddress_Profile EditText inside the onCreateView() rather than InitializeControls().
Try something like this:
private EditText txtEmailAddress_Profile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
InitializeControls(fragment_profile);
txtEmailAddress_Profile =(EditText) view.findViewById(R.id.YourEditText);
NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
#Override
public void getResult(JOM_User object) {
user = object.getUser();
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
}
});
return inflater.inflate(R.layout.fragment_profile, container, false);
}

loading fragment android best practice

I have a fragment which load data from API. I want to show loading progress as google play app does and hide or remove it when it is done.
first off all I don't want to use other libraries(http://johnkil.github.io/Android-ProgressFragment/) for this. I have bunch of code for that. I created a base fragment which show loading. but i am instantiating it in its own class. is it good to work in this way. however the loading implementation works great. MY Loading Fragment is :
public class SpinnerFragment extends Fragment {
private SpinnerFragment spinnerFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_progress, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinnerFragment = new SpinnerFragment();
}
/**
* Detach from view.
*/
#Override
public void onDestroyView() {
super.onDestroyView();
}
protected void addSpinner() {
if (!spinnerFragment.isAdded()) {
getFragmentManager().beginTransaction().add(R.id.content_frame, spinnerFragment)
.commit();
}
}
protected void removeSpinner() {
if (spinnerFragment.isAdded()) {
getFragmentManager().beginTransaction().remove(spinnerFragment).commit();
}
}
}
and i am using this class as follow:
public class List extends SpinnerFragment implements View.OnClickListener {
private ListAdapter listAdapter;
private ArrayList<ListRowItem> arrayList;
private ListView listView;
public List() {
}
public static List newInstance() {
List fragment = new List();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
addSpinner();
//loadDataFromWeb
String URL = new SqLite(getActivity()).returnDefaultURI() + "notice/"
new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1).execute(URL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
listView = (ListView) view.findViewById(R.id.content_container);
listView.setOnScrollListener(onScrollListener());
footer = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.listview_loading_footer, listView, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter == null && arrayList == null) {
arrayList = new ArrayList<>();
listAdapter = new ListAdapter(getActivity(), arrayList);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(final String response, int apiKey) {
switch (apiKey) {
case 1:
//loading complete
listViewBinding(reasponse);
removeSpinner();
break;
}
}
};
}

NullPointerException when accessing items in fragment

Does somebody know why this is not working?
Holder comes from an adapter that has my fragment included, the rest is coming from the fragment itself.
#Override
public View inflateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_entry_list, container, true);
mListView = (FlipView) rootView.findViewById(android.R.id.list);
if (mEntriesCursorAdapter != null) {
setListAdapter(mEntriesCursorAdapter);
}
mHideReadButton = (com.github.clans.fab.FloatingActionButton) rootView.findViewById(R.id.hide_read_button);
mHideReadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(mUri, mEntriesCursorAdapter.getItemId(mListView.getCurrentPage()))));
}
});
return rootView;
}
holder.mainImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment.onListItemClickFromFragment();
}
});
public void onListItemClickFromFragment(){
LayoutInflater li = getActivity().getLayoutInflater();
View v = li.inflate(R.layout.fragment_entry_list, null);
mHideReadButton = (FloatingActionButton) v.findViewById(R.id.hide_read_button);
mHideReadButton.callOnClick();
}
I fixed it by performing the fragment's action inside mHideReadButton.callOnClick() inside the Adapter.

Calling findViewById in onRefresh with fragment

I'm trying to set some view in my layout when i'm refreshing the SwipeRefreshLayout.
But I keep getting NullPointerException when i'm trying to call the findViewById.
My code:
public class LecturerFragment extends Fragment
implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout swipeRefreshLayout;
private View rootView;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_lecturer, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (savedInstanceState == null) {
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_lecturer);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
swipeRefreshLayout.setColorSchemeResources(R.color.refresh_1, R.color.refresh_2, R.color.refresh_3, R.color.refresh_4);
swipeRefreshLayout.setOnRefreshListener(this);
this.setLecturers();
}
}
private void setLecturers() {
String apiUrl = this.getResources().getString(R.string.api_url);
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(apiUrl).build();
LecturerApi api = restAdapter.create(LecturerApi.class);
api.getLecturers(new Callback<ArrayList<LecturerModel>>() {
#Override
public void success(ArrayList<LecturerModel> lecturerModels, Response response) {
//some setter code
swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swipe_refresh_lecturer);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), "Failed to fetch lecturers data", Toast.LENGTH_LONG).show();
swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swipe_refresh_lecturer);
swipeRefreshLayout.setRefreshing(false);
}
});
}
#Override
public void onRefresh() {
this.setLecturers();
}
}
I'm getting my error everytime I call the findViewById method.
assign swipeRefreshLayout only once: when you create the fragment's view:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_lecturer, container, false);
swipeRefreshLayout = rootView.findViewById(R.id.swipe_refresh_lecturer);
return rootView;
}
Remove all the other findViewByIds from your code.
Use the view you are inflating(rootView) for reference instead of getView().
Use
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_lecturer);
Instead of
swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swipe_refresh_lecturer);

Categories

Resources