Showing posts with label android-fragments. Show all posts
Showing posts with label android-fragments. Show all posts

Wednesday, March 14, 2018

Load Libgdx game to a Fragment shows a black screen on android

Leave a Comment

The following code shows how I load a Libgdx game (MyGdxGame) to a LinearLayout. on game create I set up a camera and load a small wav sound file. Texture is loaded after view is loaded.

The issue is during fragment transition to this fragment, there is a noticeable black flash and delay. Is it possible to reduce this some how and improve the fragment transition.

 public View onCreateView(LayoutInflater inflater, ViewGroup container,                          Bundle savedInstanceState) {     View view = null;     Bundle bundle = getArguments();     if (bundle != null) {         this.input = bundle.getParcelable(Utils.FRAGMENT_INPUT_KEY);     } else {         input = new FragmentInput();     }      view = inflater.inflate(R.layout.solve, container, false);     surface = (LinearLayout) view.findViewById(R.id.puzzleView);      activity = (MainActivity) getActivity();      com.badlogic.gdx.graphics.Color color = new com.badlogic.gdx.graphics.Color(Color.red(input.backColor) / 255f,             Color.green(input.backColor) / 255f,             Color.blue(input.backColor) / 255f, 1.0f);     size = input.pieceCount;     cols = input.columns;     GameData gdata = new GameData();     gdata.rows = size / cols;     gdata.columns = cols;     gdata.backColor = color;     gdata.setCategory(input.category);     if (input.rotated) {         gameView = new MyGdxGameRotate(this, gdata);     } else {         gameView = new MyGdxGame(this, gdata);     }      if (surface != null) {         AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();         View game = initializeForView(gameView, config);         surface.addView(game);     }     return view; } 

2 Answers

Answers 1

onCreateView is called before the fragment is shown, doing heavy work here means you delay showing that view (the 'black flash'), instead you should start by moving the heavy work into onResume or at least onViewCreated

Secondly, place the load on a background thread so the UI thread can continue to process the display of the fragment. The simplest way to do this in Android is to use an AsyncTask which will allow you to easily notify the UI when everything is loaded

public void onViewCreated() {     new AsyncTask<Void, Void, Void>() {         public Void doInBackground() {             //Do your loading         }          public void onPostExecute(Void aVoid) {             //Update display, play sound (on resumed fragment)         }     }.execute(); } 

If you are new to Android, be careful about leaking context with this approach

Answers 2

I am not familiar with Libgdx so my observations are not specific to Libgdx. If the view initialization takes time, and assuming that it must be done on the UI thread, maybe you can use a Framelayout and overlay a startup graphics in an ImageView that is placed on top of the current puzzleView, with its initial visibility set to visible in the xml. In the onCreateView, inflate the view as you are doing, and then only find a reference to the puzzleView, but don't do any initialization. You can then check if the view is initialized when the onResume method is called (create a new boolean field for that) and if not, then initialize it and then set the visibility of the top layer to invisible to reveal the puzzleView. The delay will still be there, but the screen will be covered by the top layer graphics until the onResume() returns, by which time (presumably) the initialization is complete. If the heavy part of the initialization can be done on a background thread, then maybe you fire off a background thread that does the the work, when the onCreateView is called, and change the visibility of the top layer and finishing part of the initialization (which almost certainly needs to be done on the UI thread) to a Runnable which should get started via a runOnUiThread() method from the background thread.

Read More

Monday, February 5, 2018

Working with fragments

Leave a Comment

I have the following design:

MainActivity      |                      /->AddingActivity      |-------Fragment One---\->DialogFragment      |-------Fragment Two          |-------Fragment Three      |-------Fragment Four 

MainActivity hold the fragments. Fragment One can start AddingActivity (with context from MainActivity) which adding data to DB and then all fragments should refresh with the new data. DialogFrgment started from FragmentOne is adding some data to SharedPreference and only the FragmentOne should know about this. MainActivity impliments DialogFragment.OnTimeSetListener (The dialog picks time) and then in MainActivity onTimeSet triggers function in Fragment One to refresh the data.

What I did for now is overridden OnCreate in each fragment and the fragment refreshes when it returns back to view. But the app is bit laggy because each fragment refreshes its neighbors and I get some fragment refreshed twice.

Can you please advise me about the correct approach to this design, and how can I make the app work more smooth and correct.

2 Answers

Answers 1

Your approach of MainActivity implementing DialogFragment.OnTimeSetListener and then notifying FragmentOne seems kind of strange.

This is how I would do it:

FragmentOne and MainActivity implement DialogFragment.OnTimeSetListener as well. However, only FragmentOne should be notified from the dialog fragment when the time changes, as it is the one responsible for setting the time. Then when this happens, FragmentOne should notify the activity:

@Override public void onTimeSet(Time time) {     ((DialogFragment.OnTimeSetListener) getActivity().onTimeSet(time); } 

When MainActivity receives the time set event, it must update the other fragments, but if possible, it should not re-create them. Just let them know the time was set so that they can update their views accordingly. Each fragment will update itself depending on what it is displaying, etc.


In case the problem persists and you still have lag, check if you do too much work on the main thread, e.g. a long-running for-loop and try to execute it on another thread.

Answers 2

Maybe you can use LocalBroadcastManager to refresh the the fragments , that way you can have the control to which fragment to refresh and not all at the same time , and you should also check if the DB is causing the lag.

Here is an example how to use LocalBroadcastManager you should implement it on your own way.

https://android--code.blogspot.com/2015/12/android-how-to-send-and-receive-local.html

Read More

Tuesday, November 7, 2017

Android best practices for fragment animations

Leave a Comment

I have activity with two tabs. Both tab uses different fragments. When a particular event occur like user click on item, I am opening another fragment in same activity.

I know how to add fragment dynamically and I also know how to animate it.

Here, how I added fragment to frameLayout in my activity:

transaction.setCustomAnimations(R.animator.object_slide_in_up, R.animator.activity_hold) transaction.add(R.id.flSellerHome, fragment) transaction.commit() 

Everything works fine in emulator and newer phones. I have tested with emulator with api 25, it works fine now flickering occur, When I am testing it with real device with api 23 it flicker little, so it doesn't affect, after then when I tested it with api 19, it flickers too much.

So my question is any best practise for doing animation.

Notes

  • My third fragment which is dynamically added contains recylerview with around 20 items from local db, and I also done db fatching in background thread.

  • No loads on main thread. recyclerview is also simple with one Image and three texts.

  • Image is also loaded using Glide and also I have override function of glide**

any help is appreciated..

4 Answers

Answers 1

I found problem is with recyclerview data updation.

I am loading data in background thread, but when notifying recyclerview, it stucks for small amout of time.

So what I have done is. I have delayed data load for same amount of time which is for animation.

I don't know it is good idea or bad idea. But it is too late for my project so I used this workaround.

Answers 2

The problem is with the RecyclerView which can update.

Try refering this link

Answers 3

I wanted to write comment to your answer, but I dont have enough rep, but I want try to advice you something, so sorry for this.

I am loading data in background thread, but when notifying recyclerview, it stucks for small amout of time.

Try to start loading, which you did, after click and show simple ProgressBar, and when data is loaded, hide progress bar, set info to your fragment and then show fragment. Then you will have all data wich you need in fragment when it is attached and can put it (data) to your adapter.

It have to look good.

Answers 4

If it occurs only for API 19 and lower, it may be a lack of performance from the device.

Maybe the problem do not come from Fragments and Animations, but from another functionality which slow down the UI thread. By functionality, I mean the way your fragments communicate together. Do they share a huge amount of data ? Or heavyweight datas ? If so, you should use Async Tasks or Threads.

Good luck !

Read More

Friday, November 3, 2017

I am getting crash in my Viewpager when I open the parent fragment for second time

Leave a Comment

Some Information: I have a fragment which contains a viewpager with three fragments. First time when I open this fragment viewpager works. second time I try to open this fragment then it crashes with following stacktrace

NOTE: This is happening on kitkat above 19 API its working fine

ViewPager setup code inside parent fragment

private void setupViewPager(ViewPager viewPager) {      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {         adapter = new ViewPagerAdapter(getChildFragmentManager());     } else {         adapter = new ViewPagerAdapter(getFragmentManager());    }     adapter.addFrag(fragment1 , "Abc");     adapter.addFrag(fragment2, "Bcd");     adapter.addFrag(fragment3, "Cdf");      viewPager.setAdapter(adapter);     viewPager.setOffscreenPageLimit(2);      myTabs.setupWithViewPager(viewPager); } 

My viewpager Adapter

class ViewPagerAdapter extends android.support.v13.app.FragmentPagerAdapter {     private final List<android.app.Fragment> mFragmentList = new ArrayList<>();     private final List<String> mFragmentTitleList = new ArrayList<>();      public ViewPagerAdapter(FragmentManager manager) {         super(manager);     }      @Override     public android.app.Fragment getItem(int position) {         return mFragmentList.get(position);     }      @Override     public long getItemId(int position) {         return super.getItemId(position);     }       @Override     public int getCount() {         return mFragmentList.size();     }      public void addFrag(android.app.Fragment fragment, String title) {         mFragmentList.add(fragment);         mFragmentTitleList.add(title);     }      @Override     public CharSequence getPageTitle(int position) {         return mFragmentTitleList.get(position);     } } 

Here is the crash stacktrace:

10-14 21:23:47.276 17601-17601/com.d.p E/AndroidRuntime: FATAL EXCEPTION: main   Process: com.d.p, PID: 17601                                                      java.lang.IllegalStateException: No activity    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1049)    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)    at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1853)    at android.app.Fragment.performActivityCreated(Fragment.java:1714)    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:908)    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)    at android.app.BackStackRecord.run(BackStackRecord.java:684)    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)    at android.os.Handler.handleCallback(Handler.java:733)    at android.os.Handler.dispatchMessage(Handler.java:95)    at android.os.Looper.loop(Looper.java:136)    at android.app.ActivityThread.main(ActivityThread.java:5017)    at java.lang.reflect.Method.invokeNative(Native Method)    at java.lang.reflect.Method.invoke(Method.java:515)    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)    at dalvik.system.NativeStart.main(Native Method) 

1 Answers

Answers 1

Finally Resolved
This is the bug in native fragments and also support v4.

When you choose other Fragment via Navigation Drawer or other thing like it, the fragment which has sub-fragments is detached. So those sub-fragments' fragmentManager(getChildFragmentManager()) is no longer exist. while those fragments return, it crashes.

So basically we will need to clean mChildFragmentManager in onDetach(). So just put below code in the fragment which is having nested fragments.

 @Override  public void onDetach() {     try {         Field childFragmentManager = android.app.Fragment.class.getDeclaredField("mChildFragmentManager");         childFragmentManager.setAccessible(true);         childFragmentManager.set(this, null);     } catch (NoSuchFieldException e) {         e.printStackTrace();     } catch (IllegalAccessException e) {         e.printStackTrace();     }     super.onDetach();    } 

Source Google issue Tracker

Read More

Saturday, October 21, 2017

How to do transverse data in Handler thread

Leave a Comment

I have an activity, which contains 2 fragments, each fragment has 2 list views, each has an adapter. So I get pretty long data in json from the server, I use AsyncTask and on post execute, I parse the data. The problem is that it freezes the loading animation for 4-5 seconds.

I have tried to use Handler thread, but the problem is still there, I must be doing something terribly wrong here.

public class DataService extends AsyncTask<String, String, Void> {      @Override         protected Void doInBackground(String... params) {          url = new URL(DATA_URL);             //Connection stuff          String jsonString = stringBuilder.toString();         jsonObject = new JSONObject(jsonString);          //Adding data in Java Objects      }       @Override     protected void onPostExecute(Void aVoid) {             super.onPostExecute(aVoid);                //Upcoming List in Fragment              allDataFragment.setUpcomingDataList(UpcomingAllDataList);              awayFragment.setUpcomingDataList(tUpcomingAwayList);              homeFragment.setUpcomingDataList(tUpcomingHomeList);                //Past List in Fragment                          allDataFragment.setPastDataList(pastAllDataList);              awayFragment.setPastDataList(pastAwayList);              homeFragment.setPastDataList(pastHomeList);          } 

I added log messages in adapter, and I can see that at the time of parsing rows it freezes, so it take all the post execute stuff in handler thread

       Handler handler= new Handler();          handler.post(new Runnable() {             @Override             public void run() {                       //Upcoming List in Fragment                      allDataFragment.setUpcomingDataList(UpcomingAllDataList);                      awayFragment.setUpcomingDataList(tUpcomingAwayList);                      homeFragment.setUpcomingDataList(tUpcomingHomeList);                        //Past List in Fragment                                  allDataFragment.setPastDataList(pastAllDataList);                      awayFragment.setPastDataList(pastAwayList);                      homeFragment.setPastDataList(pastHomeList);                   }                                }); 

I also tried to add a handler in Adapter but it fails to load UI component from there.

This is a snippet from my fragment code.

if (pastListView != null) {         PastListAdapter allGamesAdapter = new PastListAdapter(getContext(), pastAllDataList);         pastListView.setAdapter(allGamesAdapter);         } 

and in Adapter i am doing following.

  @Override     public View getView(int position, View convertView, ViewGroup parent) {              TextView vScore = (TextView) v.findViewById(R.id.v_score);             TextView date = (TextView) v.findViewById(R.id.date);             ImageView image = (ImageView) v.findViewById(R.id.iv_image);             //7 Other views               vScore.setText(dataList.get(position).getScore);             date.setText(dataList.get(position).date);               Log.d(TAG, "getView: Row");              return v;     } 

The loading animation works fine in start but at the time it starts parsing the data in adapter, it hangs t he UI thread.

5 Answers

Answers 1

Use AsyncTask to handle work items shorter than 5ms ( 5 milli seconds) in duration. Since you are getting pretty long JSON data from server, you have to look at other alternatives ( Thread, HandlerThread and ThreadPoolExecutor)

Even though you create Handler, it's running on UI Thread only. Instead of Handler, use HandlerThread

Proposed solution:

  1. Use HandlerThread to get JSON data from server. UI Thread is not blocked to get the data.

  2. Post Data from HandlerThread to Handler of UI Thread. UI Handler will take care of updating UI with data received on handleMessage(Message msg)

Useful posts:

Asynctask vs Thread vs Services vs Loader

Handler vs AsyncTask vs Thread

Why to use Handlers while runOnUiThread does the same? ( This post contains code example for above proposed solution)

Answers 2

If it's blocking the ui thread then don't do it in the ui thread

You already got an asyncTask so just use it and call your parsing json function from there

Then you can return void from that task and update your adopter from there

In other words, move your logic from onPostExecute to doInBackground

Answers 3

Use Volley instead of AsyncTask

Answers 4

at the beginning, i advise you, not be a lazy, and look to libraries

Retrofit - RESTfull client library

OKhttp - http client library

You do not need to write AsyncTasks with these libraries, and this will make your life easier and painless.

But, if you won't, ok. Let's talk about AsyncTask problems and decisions of your concerns.

AsyncTask are runs on a background computation thread and whose result is published on the UI thread. They are defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, progress updating and end of computations with updating UI. So, when it is executed, the task goes through 4 steps:

1 step. onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is basically used to configure the task, for example showing a progress bar, progress dialog or any other changes in the UI.

2 step. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

3 step. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

4 step. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

So, as you also now, if you don't want catch performance freezing, you have to return result of the computation in 2 step.

public class DataService extends AsyncTask<String, String, List<UpcomingAllDataList>> {      @Override     protected List<UpcomingAllDataList> doInBackground(String... params) {          // making HTTP request          return UpcomingAllDataList; // return results of Http request     }      @Override     protected void onPostExecute(List<UpcomingAllDataList> upcomingAllDataList) {         super.onPostExecute(upcomingAllDataList);           //Upcoming List in Fragment         allDataFragment.setUpcomingDataList(upcomingAllDataList);          // all another work      } } 

Hope, it will be usefull.

Answers 5

you should really use Retrofit for the server call + parsing.
Retrofit Github

Retrofit Site

I think the real problem is that you parse more data in setUpcomingDataList (and all the others) methods.

anyway, your example for HandlerThread is actually happening in the UI thread since Handler's default constructor takes the current thread that you construct the Handler on (which in your case is the UI thread) and post the Runnable to that thread.

anyway 2 - to see if it the methods would really work in a different thread (i guess you will get an android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. )
you can try to wrap your code with normal thread:

Thread thread = new Thread(new Runnable() {                 @Override                 public void run() {                     //Upcoming List in Fragment                     allDataFragment.setUpcomingDataList(UpcomingAllDataList);                     awayFragment.setUpcomingDataList(tUpcomingAwayList);                     homeFragment.setUpcomingDataList(tUpcomingHomeList);                       //Past List in Fragment                                 allDataFragment.setPastDataList(pastAllDataList);                     awayFragment.setPastDataList(pastAwayList);                     homeFragment.setPastDataList(pastHomeList);                 }             });             thread.start(); 

which is a really bad practice - so as I said before, use Retrofit.

Read More

Sunday, September 24, 2017

android:The specified child already has a parent. You must call removeView()

Leave a Comment

I have an activity which opens a fragment with view pager. when I change between the tabs I get this error: The specified child already has a parent. You must call removeView() on the child's parent first.

I think is the problem is from the header of the RecyclerView and I posted a new question about it here

the view pager code is:

private void mViewPager(ViewPager viewPager) {         ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());         adapter.addFragment(new a_Frag(), getString("A"));         adapter.addFragment(new b_Frag(), getString("B"));         adapter.addFragment(new c_Frag(), getString("C"));         viewPager.setAdapter(adapter);     } 

the a_frag code as example:

public class a_Frag extends Fragment {     RecyclerView recyclerView;      public a_Frag() {     }      @Override     public void onCreate(@Nullable Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public void onActivityCreated(@Nullable Bundle savedInstanceState) {         super.onActivityCreated(savedInstanceState);       }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          View view = inflater.inflate(R.layout.rv, container, false);         recyclerView = (RecyclerView) view.findViewById(R.id.rv);         recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));         recyclerView.setAdapter(new a_Adapter(getContext(), R.layout.group_header));           return recyclerView;     } 

ExpandableRecyclerView code:

public class ExpandableRecyclerView extends RecyclerView {     public ExpandableRecyclerView(Context context) {         super(context, null);         initRecycler();     }      public ExpandableRecyclerView(Context context, AttributeSet attrs) {         super(context, attrs);         initRecycler();     }      public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);         initRecycler();     }      private void initRecycler() {         setClipToPadding(false);         setItemAnimator(new DefaultItemAnimator());      }      @Override     public Parcelable onSaveInstanceState() {         //begin boilerplate code that allows parent classes to save state         Parcelable superState = super.onSaveInstanceState();          SavedState ss = new SavedState(superState);         //end          if (getAdapter() != null)             ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();          return ss;     }      @Override     public void onRestoreInstanceState(Parcelable state) {         //begin boilerplate code so parent classes can restore state         if (!(state instanceof SavedState))  // if state is not instance of out SaveState just restore in reg way         {             super.onRestoreInstanceState(state);             return;         }         // else if cast him to SavedState          SavedState ss = (SavedState) state;         super.onRestoreInstanceState(ss.getSuperState());         //end          if (getAdapter() != null)             ((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);     }      @Override     public void setAdapter(RecyclerView.Adapter adapter) {         if (!(adapter instanceof Adapter))             throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");         super.setAdapter(adapter);     }       public interface OnChildItemClickedListener {         void onChildItemClicked(int group, int position);     }      static class SavedState implements Parcelable {         public static final SavedState EMPTY_STATE = new SavedState() {         };         //required field that makes Parcelables from a Parcel         public static final Creator<SavedState> CREATOR =                 new Creator<SavedState>() {                     public SavedState createFromParcel(Parcel in) {                         return new SavedState(in);                     }                      public SavedState[] newArray(int size) {                         return new SavedState[size];                     }                 };         SparseBooleanArray stateToSave;         Parcelable superState;          SavedState() {             superState = null;         }          SavedState(Parcelable superState) {             this.superState = superState != EMPTY_STATE ? superState : null;         }          private SavedState(Parcel in) {             Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());             this.superState = superState != null ? superState : EMPTY_STATE;             this.stateToSave = in.readSparseBooleanArray();         }          @Override         public int describeContents() {             return 0;         }          @Override         public void writeToParcel(@NonNull Parcel out, int flags) {             out.writeParcelable(superState, flags);             out.writeSparseBooleanArray(this.stateToSave);         }          public Parcelable getSuperState() {             return superState;         }     }      public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {          private static final int TYPE_HEADER = 0;         SparseBooleanArray expanded = new SparseBooleanArray();         private OnChildItemClickedListener onChildItemClickedListener;          public Adapter() {         }          boolean isExpanded(int group) {             return expanded.get(group);         }          SparseBooleanArray getExpandedGroups() {             return expanded;         }          public void setExpandedGroups(SparseBooleanArray expanded) {             this.expanded = expanded;         }          public void expand(int group) {             if (isExpanded(group))                 return;              // this lines of code calculate number of shown item in recycler view. also group is counting .             int position = 0;             for (int i = 0; i < group; i++) {                 position++;                 if (isExpanded(i))                     position += getChildItemCount(i);             }             position++; // this for percent group              notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding             expanded.put(group, true); // save expanding in sparce array         }          public void collapse(int group) {             if (!isExpanded(group)) // if is not expanded . so nothing to collapse.                 return;              int position = 0;             for (int i = 0; i < group; i++) {                 position++;                 if (isExpanded(i))                     position += getChildItemCount(i); // item             }             position++;             notifyItemRangeRemoved(position, getChildItemCount(group));             expanded.put(group, false);         }          public abstract int getGroupItemCount();          public abstract int getChildItemCount(int group);          @Override         public int getItemCount() {             int count = 0;             for (int i = 0; i <= getGroupItemCount(); i++) {                 count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;             }             return count;         }          public abstract G getGroupItem(int position);          public abstract C getChildItem(int group, int position);          public Object getItem(int i) {             int group = 0;             while (group <= getGroupItemCount()) {                 if (i > 0 && !isExpanded(group)) {                     i--;                     group++;                     continue;                 }                 if (i > 0 && isExpanded(group)) {                     i--;                     if (i < getChildItemCount(group))                         return getChildItem(group, i);                     i -= getChildItemCount(group);                     group++;                     continue;                 }                 if (i == 0)                     return getGroupItem(group);             }             throw new IndexOutOfBoundsException();         }          @Override         public void onBindViewHolder(ViewHolder holder, int i) {             int group = 0;             while (group <= getGroupItemCount()) {                 if (i > 0 && !isExpanded(group)) {                     i--;                     group++;                     continue;                 }                 if (i > 0 && isExpanded(group)) {                     i--;                     if (i < getChildItemCount(group)) {                         onBindChildViewHolder((CVH) holder, group, i);                         return;                     }                     i -= getChildItemCount(group);                     group++;                     continue;                 }                 if (i == 0) {                     onBindGroupViewHolder((GVH) holder, group);                     return;                 }             }             throw new IndexOutOfBoundsException();         }          @Override         public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {             return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);         }          protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);          protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);          public abstract int getChildItemViewType(int group, int position);          @Override         public int getItemViewType(int i) {             int group = 0;             while (group <= getGroupItemCount()) {                 if (i > 0 && !isExpanded(group)) {                     i--;                     group++;                     continue;                 }                 if (i > 0 && isExpanded(group)) {                     i--;                     if (i < getChildItemCount(group))                         return getChildItemViewType(group, i);                     i -= getChildItemCount(group);                     group++;                     continue;                 }                 if (i == 0)                     return TYPE_HEADER;             }             throw new IndexOutOfBoundsException();         }          public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {             this.onChildItemClickedListener = onItemClickedListener;         }          public void onBindChildViewHolder(CVH holder, final int group, final int position) {             holder.itemView.setOnClickListener(new OnClickListener() {                 public void onClick(View v) {                     if (Adapter.this.onChildItemClickedListener != null) {                         Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);                     }                  }             });         }          public void onBindGroupViewHolder(final GVH holder, final int group) {             if (holder instanceof GroupViewHolder)                 ((GroupViewHolder) holder).setExpanded(isExpanded(group));              holder.itemView.setOnClickListener(new OnClickListener() {                 @Override                 public void onClick(View v) {                     if (isExpanded(group)) {                         collapse(group);                         if (holder instanceof GroupViewHolder)                             ((GroupViewHolder) holder).collapse();                     } else {                         expand(group);                         if (holder instanceof GroupViewHolder)                             ((GroupViewHolder) holder).expand();                     }                 }             });         }     }      public static abstract class GroupViewHolder extends ViewHolder {          public GroupViewHolder(View itemView) {             super(itemView);         }          public abstract void expand();          public abstract void collapse();          public abstract boolean isExpanded();          public abstract void setExpanded(boolean expanded);     }      public static class SimpleGroupViewHolder extends GroupViewHolder {         ImageView expandedIndicator;         TextView text;         private boolean expanded;          public SimpleGroupViewHolder(Context context) {             super(View.inflate(context, R.layout.group_header, null));              itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));             expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);             text = (TextView) itemView.findViewById(R.id.carbon_groupText);         }          public SimpleGroupViewHolder(Context context, int layout) {             super(View.inflate(context, layout, null));              itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));             expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);             text = (TextView) itemView.findViewById(R.id.carbon_groupText);         }          public void expand() {             ValueAnimator animator = ValueAnimator.ofFloat(0, 1);             animator.setInterpolator(new DecelerateInterpolator());             animator.setDuration(200);             animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {                 @Override                 public void onAnimationUpdate(ValueAnimator animation) {                     ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));                     expandedIndicator.postInvalidate();                 }             });             animator.start();             expanded = true;         }          public void collapse() {             ValueAnimator animator = ValueAnimator.ofFloat(1, 0);             animator.setInterpolator(new DecelerateInterpolator());             animator.setDuration(200);             animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {                 @Override                 public void onAnimationUpdate(ValueAnimator animation) {                     ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));                     expandedIndicator.postInvalidate();                 }             });             animator.start();             expanded = false;         }          @Override         public boolean isExpanded() {             return expanded;         }          public void setExpanded(boolean expanded) {             ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);             this.expanded = expanded;         }          public String getText() {             return text.getText().toString();         }          public void setText(String t) {             text.setText(t);         }     }  } 

the adapters are the same except for the data so I will put one example:

Adapter code example:

public class Adapter extends ExpandableRecyclerView.Adapter<Adapter.ChildViewHolder, Adapter.GroupViewHolder, String, String> {      private DatabaseHelper db;     private ArrayList List;     private int layout;       public Adapter(Context c, int resource) {         layout = resource;         db = new DatabaseHelper(c);         List = db.getRecords();//returns list     }      @Override     public int getGroupItemCount() {         return List.size() - 1;     }      @Override     public int getChildItemCount(int i) {         return 1;     }      @Override     public String getGroupItem(int i) {         return null;     }      @Override     public String getChildItem(int group, int child) {         return null;     }      @Override     protected GroupViewHolder onCreateGroupViewHolder(ViewGroup parent) {         return new GroupViewHolder(parent.getContext(), layout);     }      @Override     protected ChildViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {         View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.group_item, parent, false);         return new ChildViewHolder(rootView);     }      @Override     public void onBindGroupViewHolder(GroupViewHolder holder, int group) {         super.onBindGroupViewHolder(holder, group);          holder.setText1("A");           holder.setText2("B");     }      @Override     public void onBindChildViewHolder(ChildViewHolder holder, int group, int position) {         super.onBindChildViewHolder(holder, group, position);          holder.t1.setText("t1");           holder.t2.setText("t2");           holder.t3.setText("t3");                      holder.t4.setText("t4");      }      @Override     public int getChildItemViewType(int i, int i1) {         return 1;     }      static class GroupViewHolder extends ExpandableRecyclerView.GroupViewHolder {         ImageView expandedIndicator;         TextView text1;         TextView text2;         private boolean expanded;           GroupViewHolder(Context context, int layout) {             super(View.inflate(context, layout, null));              itemView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));             expandedIndicator = (ImageView) itemView.findViewById(R.id.groupExpandedIndicator);             text1 = (TextView) itemView.findViewById(R.id.text1);             text2 = (TextView) itemView.findViewById(R.id.text2);         }          public void expand() {             ValueAnimator animator = ValueAnimator.ofFloat(0, 1);             animator.setInterpolator(new DecelerateInterpolator());             animator.setDuration(200);             animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {                 @Override                 public void onAnimationUpdate(ValueAnimator animation) {                     ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));                     expandedIndicator.postInvalidate();                 }             });             animator.start();             expanded = true;         }          public void collapse() {             ValueAnimator animator = ValueAnimator.ofFloat(1, 0);             animator.setInterpolator(new DecelerateInterpolator());             animator.setDuration(200);             animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {                 @Override                 public void onAnimationUpdate(ValueAnimator animation) {                     ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));                     expandedIndicator.postInvalidate();                 }             });             animator.start();             expanded = false;         }          @Override         public boolean isExpanded() {             return expanded;         }          public void setExpanded(boolean expanded) {             ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);             this.expanded = expanded;         }          void setText1(String t) {             text1.setText(t);         }           void setText2(String t) {             text2.setText(t);         }     }      class ChildViewHolder extends RecyclerView.ViewHolder {         private TextView t1;         private TextView t2;         private TextView t3;         private TextView t4;           ChildViewHolder(View itemView) {             super(itemView);             t1 = (TextView) itemView.findViewById(R.id.tv1);             t2 = (TextView) itemView.findViewById(R.id.tv2);             t3 = (TextView) itemView.findViewById(R.id.tv3);             t4 = (TextView) itemView.findViewById(R.id.tv4);         }     } } 

group_header.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:clickable="true">      <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:card_view="http://schemas.android.com/apk/res-auto"         android:id="@+id/Card1"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_gravity="center"         android:layout_marginLeft="7dp"         android:layout_marginRight="7dp"         android:layout_marginTop="10dp"                 card_view:cardCornerRadius="10dp"         card_view:cardElevation="5dp">          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"             xmlns:app="http://schemas.android.com/apk/res-auto"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="right"             android:orientation="horizontal">              <TextView                 android:id="@+id/text1"                 style="@style/MyLargeTextAppearance"                 android:layout_width="0dp"                 android:layout_height="wrap_content"                 android:layout_weight="1"                 android:gravity="center"                 android:padding="16dp"                 android:textColor="@color/highlight"                 android:textStyle="bold" />           </LinearLayout>     </android.support.v7.widget.CardView>      <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:card_view="http://schemas.android.com/apk/res-auto"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_below="@id/Card1"         android:layout_gravity="center"         android:layout_marginLeft="7dp"         android:layout_marginRight="7dp"         android:layout_marginTop="1dp"         card_view:cardCornerRadius="10dp"         card_view:cardElevation="5dp">          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"             xmlns:app="http://schemas.android.com/apk/res-auto"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="right"             android:orientation="horizontal">              <TextView                 android:id="@+id/text2"                 style="@style/MyLargeTextAppearance"                 android:layout_width="0dp"                 android:layout_height="wrap_content"                 android:layout_weight="1"                 android:gravity="center"                 android:padding="16dp"                 android:textColor="@color/highlight"                 android:textStyle="bold" />              <ImageView                 android:id="@+id/groupExpandedIndicator"                 android:layout_width="24dp"                 android:layout_height="24dp"                 android:layout_gravity="center_vertical"                 android:layout_marginEnd="16dp"                 android:layout_marginRight="16dp"                 app:srcCompat="@drawable/ic_expand_more" />         </LinearLayout>     </android.support.v7.widget.CardView> </RelativeLayout> 

group_item.xml:

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:card_view="http://schemas.android.com/apk/res-auto"     android:id="@+id/card"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_gravity="center"     android:layout_marginLeft="7dp"     android:layout_marginRight="7dp"     android:layout_marginTop="10dp"     card_view:cardCornerRadius="10dp"     card_view:cardElevation="5dp">      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:background="@color/materialGray"         android:orientation="vertical"         android:padding="@dimen/activity_horizontal_margin">           <TextView             android:id="@+id/t1"             style="@style/MyLargeTextAppearance"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="center"             android:text="TextView" />          <View             android:layout_width="match_parent"             android:layout_height="1dp"             android:background="@color/separatorViewBackground" />          <TextView             android:id="@+id/t2"             style="@style/MyLargeTextAppearance"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="center"             android:text="TextView" />          <View             android:layout_width="match_parent"             android:layout_height="1dp"             android:background="@color/separatorViewBackground" />          <TextView             android:id="@+id/t3"             style="@style/MyLargeTextAppearance"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="center"             android:text="TextView"/>          <View             android:layout_width="match_parent"             android:layout_height="1dp"             android:background="@color/separatorViewBackground" />          <TextView             android:id="@+id/t4"             style="@style/MyLargeTextAppearance"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:gravity="center"             android:text="TextView" />      </LinearLayout> </android.support.v7.widget.CardView> 

1 Answers

Answers 1

Try changing to:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){     View view = inflater.inflate(R.layout.rv, container, false);     recyclerView = (RecyclerView) view.findViewById(R.id.rv);     recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));     recyclerView.setAdapter(new a_Adapter(getContext(), R.layout.group_header));      if (recyclerView != null) {        return recyclerView;     }       return null; } 
Read More

Monday, August 28, 2017

java.lang.IllegalStateException: Fragment no longer exists for key f0: index 1

Leave a Comment

I am having couple of fragment in an Activity. After doing some process I am closing the fragment using the below code.

if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {                         getActivity().getSupportFragmentManager().popBackStackImmediate(); } 

But on line popBackStackImmediate() its throwing the error

    Process: com.TestProject.testpro, PID: 17966  java.lang.IllegalStateException: Fragment no longer exists for key f0: index 1      at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:879)      at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:215)      at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1481)      at android.view.View.dispatchRestoreInstanceState(View.java:14746)      at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3121)      at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3127)      at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3127)      at android.view.View.restoreHierarchyState(View.java:14724)      at android.support.v4.app.Fragment.restoreViewState(Fragment.java:475)      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1329)      at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)      at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:807)      at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2360)      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)      at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)      at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:823)      at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:776)      at com.TestProject.testpro.application.fragments.WFMUpgradeToAffinityFragmentAN$WFMStoreProfileIdReceiver.onReceive(WFMUpgradeToAffinityFragmentAN.java:1064)      at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)      at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)      at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)      at android.os.Handler.dispatchMessage(Handler.java:102)      at android.os.Looper.loop(Looper.java:148)      at android.app.ActivityThread.main(ActivityThread.java:5417)      at java.lang.reflect.Method.invoke(Native Method)      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

There is no other crash which close the fragment. I cant find the exact solution for this issue. Please help me on this.

Edited:

I am using the below function to call the fragment.

void showContentFragment(Fragment newFragment, String backStackName) {     //Log.e(TAG, "showContentFragment- " + "BackstackName: "+ backStackName);     FragmentManager mFragmentManager = getActivity().getSupportFragmentManager();     if (newFragment != null) {         //updateNavigation(backStackName);         FragmentTransaction ft = mFragmentManager.beginTransaction();         ft.replace(R.id.fragment_container, newFragment);         if (backStackName != null && !backStackName.isEmpty()) {             ft.addToBackStack(backStackName);         }          ft.commit();     } } 

5 Answers

Answers 1

Please follow this steps to add fragments from your activity

 getSupportFragmentManager().beginTransaction()                 .replace(R.id.frame, yourFragment, yourFragment.class.getSimpleName()).addToBackStack(yourFragment.class.getSimpleName())                 .commit(); 

using this code for calling popBackStack() from your fragment

    if (getFragmentManager().getBackStackEntryCount() > 0) {                         getFragmentManager().popBackStack(); } 

Make sure that you are importing right fragment class

import android.support.v4.app.Fragment; 

Answers 2

add Below code in your Fragment classes , according to doc it returns the Transition to use to move Views out of the Scene when the Fragment is preparing to close.

@Override     public Object getReturnTransition() {         return super.getReturnTransition();     } 

Answers 3

Your stacktrace shows you are using both a ViewPager and manipulating the backstack yourself.

This is probably not a good idea - either let your ViewPager manage the backstack (which it does well) or manage it entirely yourself.

Note that in managing the backstack yourself you will have to account for restoring instance state (which features in your stacktrace) and the Fragment lifecycle.

This means in conditions of low memory your Activity and Fragments will be stopped. If you have not saved the instance state correctly, when they are restarted you will get errors like the above one. If the workflow of your Fragments is simple, you can avoid all of this by using a ViewPager.

Answers 4

public void showContentFragment(Fragment fragment, Bundle bundle, boolean addToBackStack) {         if (bundle != null)             fragment.setArguments(bundle);          tag = fragment.getClass().getSimpleName();         FragmentTransaction ft = getSupportFragmentManager().beginTransaction();         ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);         ft.replace(R.id.container_internal, fragment, tag);         fragment.setRetainInstance(true); // IMPORTANT          if (addToBackStack)             ft.addToBackStack(tag);          try {             ft.commit();          } catch (Exception ex) {             ex.printStackTrace();             ft.commitAllowingStateLoss();         } 

Answers 5

First, you don't need to call getActivity().getSupportFragmentManager(). getFragmentManager() is enough to call FragmentManager.

If you are in Support Fragment getFragmentManager() will give you supportFragmentManager() or it will give you app.Fragment Manager.

If you are calling the PopBackstack inside the ViewPager, it won't work. If you are using viewPager inside another fragment. you should call popBackstack only in the parent fragment. Not in the viewPager.

Try the below code it will clear the stack according to the back stack name.

getFragmentManager.popBackStackImmediate(YourBackStackName, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

Docs: https://developer.android.com/reference/android/app/FragmentManager.html#popBackStackImmediate(java.lang.String, int)

Hope it helps :)

Read More

Thursday, June 1, 2017

Curiosity Down/Up Swipe Animation & Fragments Populating Based On posts date

Leave a Comment

** in a nutshell: i want the scroll animation as shown in the gif, when the user swipes down/up it goes directly to the item, and its like a fling animation.

For the Date fragments, i guess its a horizontal Recyclerview.

What am looking as an answer is, a code example of the scroll animation, and a way to do the date thing, where i can auto populate the fragments based on the dates.

I've asked before about this and wmy question was not that clear. this app includes a swipe down/up style.

When u swipe down or up, the app doesnt let you swipe like a normal Scrollview, instead from the first touch (up for example) it navigates you to the next post.

Important note is the post/item in full size (item layout match_parent ?).

Also, every post has a date, and the app includes a calendar, when you swipe left or right, you navigates to dates and based on dates you get the posts.

What i want, hints or ways to do something like this. i'd love to provide a code but i've tried to draw the way up in my mind but couldn't think in of a logical way.

For fragments, i guess they're taking the now date, and the oldest date in the post, and based on that they're making (looping) fragments, each fragment has to load a posts based on the date (query to the API which gives date as param?).

Anyway, here's a GIF of the app which explains what im talking about. Im going to setup a bounty for this question, as im eager to achieve such a feature like this in my app.

https://gfycat.com/JadedMenacingAmericanalligator

1 Answers

Answers 1

I have not tried this by myself but I would like to help may be this will do the work First use this library for the vertical scrolling one at a time https://github.com/lsjwzh/RecyclerViewPager or may be this one https://github.com/castorflex/VerticalViewPager

or may be use the pagersnaphelper of v7 support library like this

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); SnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); 

and for the horizontal scrolling you can use these libraries may be if you apply little bit of logic you will achieve it.

https://medium.com/@ali.muzaffar/looping-infinite-viewpager-with-page-indicator-in-android-ce741f25702a

https://github.com/antonyt/InfiniteViewPager

Changing ViewPager to enable infinite page scrolling

let me know if it works.

Read More

Monday, May 8, 2017

Data is not inserting to database when image is null

Leave a Comment

I want to store data into the database and want to upload an image in optional.

It means that if i am inserting the record without adding image then it will store in database without the image name.

right now when i am fill the data and insert an image then it is storing in the database if i don't select any image and i add only data then in database the data is not inserted and showing me blank value in every field

I tried a lot but not getting the required output.

My code main.java

    buy_image1.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 selectImage();                 edit.putInt("ImageID", 1);                 edit.commit();               }         });          public void selectImage()     {         i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);         startActivityForResult(i, RESULT_LOAD_IMAGE);         /*i.putExtra("crop", "true");         i.putExtra("outputX", 512);         i.putExtra("outputY", 512);         i.putExtra("aspectX", 1);         i.putExtra("aspectY", 1);         i.putExtra("scale", true);     */     }     public void onActivityResult(int requestCode, int resultCode, Intent data)     {         super.onActivityResult(requestCode, resultCode, data);         if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {             final int IMAGE_MAX_SIZE = 1200000; // 1.2MP              Uri selectedImage = data.getData();             int imgid = 0;             String[] filePathColumn = {MediaStore.MediaColumns.DATA};             Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);             cursor.moveToFirst();              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);             picturePath = cursor.getString(columnIndex);             cursor.close();             Log.d("Value", picturePath);             fileName = new File(picturePath).getName();             // imgname.setText(fileName);              String fileNameSegments[] = picturePath.split("/");             fileName = fileNameSegments[fileNameSegments.length - 1];              // MyParams.put("filename", fileName);             Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);              sp = getActivity().getSharedPreferences("Image ID", Context.MODE_PRIVATE);             imgid = sp.getInt("ImageID", 0);             Log.d("IMGID", Integer.toString(imgid));               BitmapFactory.Options options =null;             options = new BitmapFactory.Options();             options.inSampleSize = 5;             bitmap = BitmapFactory.decodeFile(picturePath, options);             ByteArrayOutputStream stream = new ByteArrayOutputStream();             bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);              byte[] byte_arr = stream.toByteArray();             // Encode Image to String             encodedString = Base64.encodeToString(byte_arr, 0);               if(imgid == 1) {                 buy_image1.setImageBitmap(yourSelectedImage);                 img1 = fileName;                 encodedStringIMG1 = encodedString;             }else if(imgid == 2){                  buy_image2.setImageBitmap(yourSelectedImage);                 img2 = fileName;                 encodedStringIMG2 = encodedString;              }         else{                 Log.d("IMGID","IMAGE ID IS 0");             }     }     private void InsertWodinformation() {          service(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,                 strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,                 strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,img1,encodedStringIMG1,img2,encodedStringIMG2);     } private void service(         String strwodname,String strbranch,         String strcontactperson, String strcontact,         String strwhatsapp, String stremail, String strspinnercity,         String straddress, String opendate1, String birthdate, String ani,         String strpancard, String strtinnumber, String strbankname, String strbankholdername         ,String strbankac,String strbankcity, String strifsccode,String strsecuritycheque,String strrefrence1,         String strrefrence2,String strremarks,String i1,String encode1,String i2,String encode2   ) {          class AddVisitclass extends AsyncTask<String, Void, String> {             ProgressDialog loading;             RegisterUserClass ruc = new RegisterUserClass();              @Override             protected void onPreExecute() {                 super.onPreExecute();             }             @Override             protected String doInBackground(String... params) {                   HashMap<String, String> param = new HashMap<String, String>();                   /*param.put("firm", params[1]);                 param.put("oname", params[2]);                 param.put("pname1", params[3]);                 param.put("pname2", params[4]);                 */                 param.put("wname", params[0]);                 param.put("branch", params[1]);                 param.put("cname", params[2]);                 param.put("contact", params[3]);                 param.put("whatsapp", params[4]);                 param.put("email", params[5]);                  param.put("city", params[6]);                 param.put("address", params[7]);                 param.put("odate", params[8]);                 param.put("bdate", params[9]);                 param.put("adate", params[10]);                 param.put("pancard", params[11]);                 param.put("tinno", params[12]);                 param.put("bnm", params[13]);                 param.put("bank_ac_holder", params[14]);                 param.put("bank_ac_no", params[15]);                 param.put("bcity", params[16]);                 param.put("ifsc_code", params[17]);                 param.put("cheque", params[18]);                 param.put("ref1", params[19]);                 param.put("ref2", params[20]);                 param.put("remarks", params[21]);                  param.put("pan", params[22]);                 param.put("epan", params[23]);                 param.put("aadhar", params[24]);                 param.put("eaadhar", params[25]); /*                   param.put("light", params[26]);                 param.put("elight", params[27]);                  param.put("vat", params[28]);                 param.put("evat", params[29]);                  param.put("vcard", params[30]);                 param.put("evcard", params[31]);                  param.put("shop", params[32]);                 param.put("eshop", params[33]); */                    param.put("username",uid);                 String result = ruc.sendPostRequest(url_addwod, param);                 Log.d("Result", result);                 Log.d("Data", param.toString());                 return result;             }             //@Override             protected void onPostExecute(String result) {                 super.onPostExecute(result);                 //loading.dismiss();                   Toast.makeText(getActivity(), "W.O.D. added successfully...!!!", Toast.LENGTH_LONG).show();                 /* FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();                 TabFragment mFrag = new TabFragment();                 t.replace(com.Weal.sachin.omcom.R.id.framelayout, mFrag);                 t.commit();                 */             }         }         AddVisitclass regi = new AddVisitclass();         regi.execute(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,                 strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,                 strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,i1,encode1,i2,encode2);     } 

And one more thing when image is uploading to the server it is generating the lower size but i want it in default size.

7 Answers

Answers 1

The best way to store images/files data is to save the images to the device storage resource (e.g internal memory or external),then you have the image URL/URI saved in your database (instead of having blob field in the database), and to display it all you have to do is to retrieve the file URL and display it on the device.

I hope this gives you a better solution for this issue.

Answers 2

The best way to save images are save them in your computer or device you are using and pass the path (location) of the image through a sql query to the database and when you want to access the image get the location of the image from the database and display.

following link will help you to understand http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Answers 3

Consider first compressing your images, to reduce the size of the image for storage. You have three options here, first you can get the base64 representation of the image, which is a string then store it , or get the byte array output and still store it. And lastly store the uri reference for the image located on the phone. Though i would not recommend this approach, because it is subjected to path changes and user deletion.

Here is a great library that uses google webp.WebP is a modern image format that provides superior lossless and lossy compression for images.WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index. Link to library.

Here is a galore of code snippets that can perform your request!

private static String CompressJPEG(Bitmap bitmap) {         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);         byte[] byteFormat = stream.toByteArray();         return Base64.encodeToString(byteFormat, Base64.DEFAULT);     }  private static byte[] CompressJPEGByteArray(Bitmap bitmap) {         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);         return stream.toByteArray(); 
    }   private static String CompressPNG(Bitmap bitmap) {         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);         byte[] byteFormat = stream.toByteArray();         return Base64.encodeToString(byteFormat, Base64.DEFAULT);     } 
  private static byte[] CompressPNGByteArray(Bitmap bitmap) {         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);         return stream.toByteArray(); 
    }     private static Bitmap RevertImageBase64(String encodedImage) {         byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);         return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);     }  public static Bitmap RevertFromByteArray(byte[] arr) {         return BitmapFactory.decodeByteArray(arr, 0, arr.length);     } 

Here is also code to get the extension from a uri.

 public static void GetExtensionFromContentURI(Context context, Uri uri) {         ContentResolver cR = context.getContentResolver();         MimeTypeMap mime = MimeTypeMap.getSingleton();         String ext = mime.getExtensionFromMimeType(cR.getType(uri));      } 

Hope this helps :)

Answers 4

You have to covert bitmap to BLOB format to save it ti db llook below code :

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);     byte[] byteArray = byteArrayOutputStream.toByteArray();     String encodedData = Base64.encodeToString(byteArray, Base64.DEFAULT);      dba.insertPhoto(byteArray); 

Answers 5

Regarding the size issue you mentioned, in onActivityResult(), the statement:

options.inSampleSize = 5; 

could be the reason for the file to be smaller than the original image.

This is needed for the ImageView. Before compressing, keep a non compressed coopy for transmission to the server.

To troubbleshoot the insert of the image you need to post:

  1. If the column in the database is defined as "not null"
  2. A Log.d() of the value it is sending to the server when no picture is selected.
  3. The code on the server that receives the data and performs runs the insert.

Answers 6

Refactoring code like below might help you. Don't take method names, variable names and other parts as a real example. I wanted to give you a bird-eye view of sample design.

//controller of user request. handleRequest(){     String imagePath=null;     if(imageExists){ //if user sent image to server.         imagePath=saveImageAndReturnImagePath(...);     }      saveRecordToDB(request.getText(), imagePath); }    //save image to disk and return image path. private String saveImageAndReturnImagePath(...){     //do image manipulation here, save image to disk, return path.     return imagePath; }  //insert a new record to db. private void saveRecordToDB(String text, imagePath){     Record a=new Record(text, imagePath);     dao.save(a); } 

Answers 7

The simplest way to cache images . is to use JakeWharton/picasso2-okhttp3-downloader Here's an example :

       OkHttpClient okHttpClient = new OkHttpClient();     okHttpClient.networkInterceptors().add(new Interceptor() {         @Override         public Response intercept(Chain chain) throws IOException {             Response originalResponse = chain.proceed(chain.request());             return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();         }     });     try{           okHttpClient.setCache(new Cache(this.getCacheDir(), Integer.MAX_VALUE));         OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);         Picasso picasso = new Picasso.Builder(this).downloader(okHttpDownloader).build();         picasso.load("pucul").error(R.drawable.teacher).into(imgvw);     }     catch (Exception e){ 

add this to your gradle file

compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0' 

Source :

Read More

Monday, April 3, 2017

Fragment vs Activity canvas drawing on android

Leave a Comment

I designed a surfaceview, where it's canvas is drawn using a thread (Game loop). The Game loop draws 300 small images.

If I load this surfaceview on activity, the time to execute a frame is 5- 10 ms lower than if I load it on a fragment (withing an activity).

Test results 300 images loop- activity (24 millsec) , Fragment (32 millsec).

What is the reason behind this? How can I improve the performance in Fragment?

Here is my code. The loop at the end is the bottleneck. clusters list could have 300 items to draw.

public List<PCluster> clusters = new ArrayList<PCluster>();      public void doDraw(Canvas canvas) {      try {         if (canvas == null) {             return;         }         super.draw(canvas);          canvas.drawColor(backColor);         if (waitTillLoad) {             return;         }      } catch (Exception ex) {     }     final int savedState = canvas.save();     try {          minX = (int) (((viewWidth / mScaleFactor) - Gen.screenSizeWidth) / 2) * Utils.VIEW_SIZE;         minY = (int) (((viewHeight / mScaleFactor) - Gen.screenSizeHeight) / 2) * Utils.VIEW_SIZE;          if (mPosX > maxX) {             mPosX = maxX;         }         if (mPosX < minX) {             mPosX = minX;         }         if (mPosY > maxY) {             mPosY = maxY;         }         if (mPosY < minY) {             mPosY = minY;         }           canvas.scale(mScaleFactor, mScaleFactor);         canvas.translate(mPosX, mPosY);          long startTime = System.currentTimeMillis();         if (!showBackground) {              for (PCluster cluster : clusters) {                 if (cluster.isVisible) {                     canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,                             cluster.BoardLocation.top, null);                 }             }             Log.d("myApp", "   " + (System.currentTimeMillis() - startTime));         }      } catch (Exception ex) {     } finally {         canvas.restoreToCount(savedState);     } } 

This is main activity layout. @+id/fragment is used to load the layout below which has SurfaceView LinearLayout where the surface view is inserted at run time and where the drawing happens.

Main Layout

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >  <LinearLayout     android:id="@+id/fragment_fake"     android:layout_width="0dp"     android:layout_height="0dp"     android:gravity="center"     android:orientation="vertical"     android:layout_above="@+id/fragment"/>  <LinearLayout     android:id="@+id/fragment"     android:layout_width="fill_parent"     android:layout_height="fill_parent"      android:gravity="center"      android:orientation="vertical"     android:layout_above="@+id/fragment_ad"/>   <fragment     android:id="@+id/fragment_ad"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:layout_alignParentBottom="true"     class="controllers.AdFragment" />  </RelativeLayout> 

Game Layout with surface view

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">   <LinearLayout     android:id="@+id/surfaceView"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"/>  <include     android:id="@+id/gamesettingpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_alignParentTop="true"     layout="@layout/gameoption_panel" />  <include     android:id="@+id/scorepanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_gravity="top"     android:layout_alignParentTop="true"     android:layout_centerHorizontal="true"     android:gravity="center_horizontal"     layout="@layout/scorepanel" />  <include     android:id="@+id/chaetpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_gravity="bottom"     layout="@layout/gamecheat_panel" />  <include     android:id="@+id/finishpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_centerHorizontal="true"     android:gravity="center_horizontal"     android:layout_alignParentTop="true"     layout="@layout/finishedpanel" /> 

0 Answers

Read More

Friday, March 3, 2017

Android fitsSystemWindows not working when replacing fragments

Leave a Comment

I have SingleFramgnetActivity whose purpose is only to hold and replace fragments inside it.

layout looks like this:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:gravity="center_horizontal"     android:orientation="vertical"     tools:context=".SingleFragmentActivity"     >      <include layout="@layout/toolbar"/>      <FrameLayout         android:id="@+id/content"         android:layout_width="match_parent"         android:layout_height="match_parent"         /> </LinearLayout> 

I'm replacing the Fragments inside the FrameLayout. When I set the fitsSystemWindows to true on the Fragment layout, it is not responding. Actually it is working only when Activity is created, but once I replace the Fragment inside the FrameLayout, the fitsSystemWindows parameter is ignored and the layout is below the status bar and navigation bar.

I found some solution with custom FrameLayout which is using deprecated methods, but for some reason it is not working for me (same result as with normal FrameLayout) and I also do not like the idea to use deprecated methods.

1 Answers

Answers 1

Your FrameLayout is not aware of window inset sizes, because it's parent - LinearLayout hasn't dispatched him any. As a workaround, you can subclass LinearLayout and pass insets to children on your own:

@TargetApi(Build.VERSION_CODES.KITKAT_WATCH) @Override public WindowInsets onApplyWindowInsets(WindowInsets insets) {     int childCount = getChildCount();     for (int index = 0; index < childCount; index++)         getChildAt(index).dispatchApplyWindowInsets(insets); // let children know about WindowInsets      return insets; } 

You can have a look to my this answer, which will explain detailed how this works, and also how to use ViewCompat.setOnApplyWindowInsetsListener API.

Read More

Sunday, February 26, 2017

RecyclerView onBindViewHolder called only once inside Tab layout

Leave a Comment

I've four tabs and four fragments (each one for each tab).

Each fragment has a vertical recycler view. Since all fragments view look similar I'm re-using the same layout file, same recycler view items and same adapter.

The issue is that only one item is loaded under the first tab and third tab and fourth tab, While the second tab successfully loads the entire data.

I hope image added below gives better understanding regarding the issue.

enter image description here

Here is my adapter code

public class OthersAdapter extends RecyclerView.Adapter<OthersAdapter.OthersViewHolder> {      private final Context context;     private final ArrayList<LocalDealsDataFields> othersDataArray;     private LayoutInflater layoutInflater;      public OthersAdapter(Context context, ArrayList<LocalDealsDataFields> othersDataArray) {         this.context = context;         this.othersDataArray = othersDataArray;         if (this.context != null) {             layoutInflater = LayoutInflater.from(this.context);         }     }      class OthersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {         TextView othersSmallTitleTextView;         ImageView othersImageView;          OthersViewHolder(View itemView) {             super(itemView);             othersSmallTitleTextView = (TextView) itemView.findViewById(R.id.others_small_title);             othersImageView = (ImageView) itemView.findViewById(R.id.others_image);             itemView.setOnClickListener(this);         }          @Override         public void onClick(View view) {             Intent couponDetailsItem = new Intent(context, LocalDealsActivity.class);             Bundle extras = new Bundle();             extras.putString(Constants.SECTION_NAME, context.getString(R.string.local_deals_section_title));             // Add the offer id to the extras. This will be used to retrieve the coupon details             // in the next activity             extras.putInt(Constants.COUPONS_OFFER_ID, othersDataArray.get(                     getAdapterPosition()).getLocalDealId());             couponDetailsItem.putExtras(extras);             context.startActivity(couponDetailsItem);         }     }      @Override     public OthersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View view = layoutInflater.inflate(R.layout.others_items, parent, false);         return new OthersViewHolder(view);     }      @Override     public void onBindViewHolder(OthersViewHolder holder, int position) {         String lfImage = othersDataArray.get(position).getLocalDealImage();         String lfCategoryName = othersDataArray.get(position).getLocalDealSecondTitle();         if (lfCategoryName != null) {             // Set the second title             holder.othersSmallTitleTextView.setText(lfCategoryName);         }         if (lfImage != null) {             if (!lfImage.isEmpty()) {                 // Get the Uri                 Uri lfUriImage = Uri.parse(lfImage);                 // Load the Image                 Picasso.with(context).load(lfUriImage).into(holder.othersImageView);             }         }     }      @Override     public int getItemCount() {         return othersDataArray.size();     } } 

I like to point out couple of things -

  • I've checked other answers on Stack Overflow. They talk about setting the recycler view layout_height to wrap_content. This isn't the issue as the layout_height is already wrap_content and also the second tab loads all the data as expected.

  • And some others answers mentioned to used same versions for all support libraries and I'm already using 25.1.0 version for all the support libraries.

  • Size of the data array is 20 and returning 20 from the adapter's getItemCount() method.

  • The data array has the expected number of items in it and they are not null or empty.

  • Clean build, invalidate/caches doesn't work either.

  • Finally, I'm using FragmentStatePagerAdapter to load the fragments when the tabs are in focus.

EDIT:

This is how I'm parsing the JSON data received

private void parseLocalDeals(String stringResponse) throws JSONException {     JSONArray localJSONArray = new JSONArray(stringResponse);     // If the array length is less than 10 then display to the end of the JSON data or else     // display 10 items.     int localArrayLength = localJSONArray.length() <= 20 ? localJSONArray.length() : 20;     for (int i = 0; i < localArrayLength; i++) {         // Initialize Temporary variables         int localProductId = 0;         String localSecondTitle = null;         String localImageUrlString = null;         JSONObject localJSONObject = localJSONArray.getJSONObject(i);         if (localJSONObject.has(JSONKeys.KEY_LOCAL_DEAL_ID)) {             localProductId = localJSONObject.getInt(JSONKeys.KEY_LOCAL_DEAL_ID);         }         if (localJSONObject.has(JSONKeys.KEY_LOCAL_DEAL_CATEGORY)) {             localSecondTitle = localJSONObject.getString(JSONKeys.KEY_LOCAL_DEAL_CATEGORY);         }         if (localJSONObject.has(JSONKeys.KEY_LOCAL_DEAL_IMAGE)) {             localImageUrlString = localJSONObject.getString(JSONKeys.KEY_LOCAL_DEAL_IMAGE);         }          if (localImageUrlString != null) {             if (!localImageUrlString.isEmpty()) {                 // Remove the dots at the start of the Product Image String                 while (localImageUrlString.charAt(0) == '.') {                     localImageUrlString = localImageUrlString.replaceFirst(".", "");                 }                 // Replace the spaces in the url with %20 (useful if there is any)                 localImageUrlString = localImageUrlString.replaceAll(" ", "%20");             }         }          LocalDealsDataFields localDealsData = new LocalDealsDataFields();         localDealsData.setLocalDealId(localProductId);         localDealsData.setLocalDealSecondTitle(localSecondTitle);         localDealsData.setLocalDealImage(localImageUrlString);          localDealsDataArray.add(localDealsData);     }      // Initialize the Local Deals List only once and notify the adapter that data set has changed     // from second time. If you initializeRV the localDealsRVAdapter at an early instance and only     // use the notifyDataSetChanged method here then the adapter doesn't update the data. This is     // because the adapter won't update items if the number of previously populated items is zero.     if (localDealsCount == 0) {         if (localArrayLength != 0) {             // Populate the Local Deals list             // Specify an adapter             localDealsRVAdapter = new OthersAdapter(context, localDealsDataArray);             localDealsRecyclerView.setAdapter(localDealsRVAdapter);         } else {             // localArrayLength is 0; which means there are no rv elements to show.             // So, remove the layout             contentMain.setVisibility(View.GONE);             // Show no results layout             showNoResultsIfNoData(localArrayLength);         }     } else {         // Notify the adapter that data set has changed         localDealsRVAdapter.notifyDataSetChanged();     }     // Increase the count since parsing the first set of results are returned     localDealsCount = localDealsCount + 20;     // Remove the progress bar and show the content     prcVisibility.success(); } 

parseLocalDeals method is inside a helper class and it is called by using initializeHotels.initializeRV();

initializeRV() initializes the Recycler view, makes a network call to the server and the received data is passed to the parseLocalDeals method. initializeHotels being an instance variable of the Helper class.

EDIT 2:

For those who wants to explore the code in detail, I've moved the part of the code to another project and shared it on Github. Here is the link https://github.com/gSrikar/TabLayout and to understand the hierarchy check out the README file.

Can anyone tell me what I'm missing?

3 Answers

Answers 1

Not much of an answer but too long for a comment.

I have duplicated (almost) your adapter code and it fully works for me. I believe I have done the same as you. I'm using the same layout file, the same item & same adapter for all tabs. I think there are no problems with your adapter code.

I say 'almost' because I had to change a couple of things since I don't have access to your data. I changed your LocalDealsDataField model to include a BitmapDrawable & I changed onBindViewHolder() to handle it.

    BitmapDrawable lfImage = othersDataArray.get(position).getLocalDealImage();     holder.othersImageView.setBackground(lfImage); 

Since there seems to be no problem with your adapter, I would focus on getting the data or setting up the adapter as your problem. Sorry I can't be of help beyond that.

FYI, here's how I setup the adapter in onCreateView()

    rootView = inflater.inflate(R.layout.recycler_view, container, false);     mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);     mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));     mAdapter = new OthersAdapter(this.getContext(), list);     mRecyclerView.setAdapter(mAdapter); 

Answers 2

I have looked at your code, problem is same as explained by @ardock

Solution i would like to propose,

You have to change your code at 3 place ::

  1. Inside all Fragment You are using in ViewPager Don't call initializeRESPECTIVEView() from onCreateView method.

  2. Inside LocalFragment make a list of Fragments you are going to use with ViewPager and pass it to BottomSectionsPagerAdapter. and return Fragment from that list from getItem(int position) of BottomSectionsPagerAdapter.

  3. Add Following code to LocalFragment inside useSlidingTabViewPager().

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

       ` @Override     public void onTabSelected(TabLayout.Tab tab) {      }      @Override     public void onTabUnselected(TabLayout.Tab tab) {      }      @Override     public void onTabReselected(TabLayout.Tab tab) {      } });` 

    //Call Respective fragment initializeRESPECTIVEView() method from onTabSelected , you can get fragment instance from list you passed to BottomSectionsPagerAdapter

Answers 3

1. Proposed fix for Marshmallow and Nougat devices. Work in progress

Check your LocalFragment getItem() method using breakpoints.

If you select one page, next page is also initialised and you are sharing the recyclerView etc.

I would move the initialisation outside of getItem() as suggested here:

ViewPager is default to load the next page(Fragment) which you can't change by setOffscreenPageLimit(0). But you can do something to hack. You can implement onPageSelected function in Activity containing the ViewPager. In the next Fragment(which you don't want to load), you write a function let's say showViewContent() where you put in all resource consuming init code and do nothing before onResume() method. Then call showViewContent() function inside onPageSelected. Hope this will help

Read these related questions (the first has possible workarounds to hack the limit to zero):

ViewPager.setOffscreenPageLimit(0) doesn't work as expected

Does ViewPager require a minimum of 1 offscreen pages?

Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:

Requested offscreen page limit 0 too small; defaulting to 1

viewPager.setOffscreenPageLimit(couponsPagerAdapter.getCount());

public void setOffscreenPageLimit(int limit) {     if (limit < DEFAULT_OFFSCREEN_PAGES) {         Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to "                 + DEFAULT_OFFSCREEN_PAGES);         limit = DEFAULT_OFFSCREEN_PAGES;     }     if (limit != mOffscreenPageLimit) {         mOffscreenPageLimit = limit;         populate();     } } 

2. You are loading a wrong page on Marshmallow and Nougat devices

FragmentStatePagerAdapter first call to getItem() wrong on Nougat devices

This ended up having nothing to do with the FragmentStatePagerAdapter code. Rather, in my fragment, I grabbed a stored object from an array using the string ("id") that I passed to the fragment in init. If I grabbed that stored object by passing in the position of the object in the array there was no problem. Only occurs in devices with Android 7.

FragmentStatePagerAdapter - getItem

A FragmentStatePager adapter will load the current page, and one page either side. That is why it logs 0 and 1 at the same time. When you switch to page 2, it will load page 3 and keep page 1 in memory. Then when you get to page 4 it will not load anything, as 4 was loaded when you scrolled to 3 and there is nothing beyond that. So the int that you're being given in getItem() is NOT the page that is currently being viewed, is the one being loaded into memory. Hope that clears things up for you

These comments are confirmed in this branch and commit

All pages load correctly on Lollipop emulator, last page has an extra issue, see OthersFragment:

enter image description here

enter image description here

Read More