Nested Fragment with backstack Resume - android

In my application there are several fragments in an activity and I am maintaining a backStack for these fragment. Everything is okay, but there is a nested fragment among them. When I put it into backStack and again resume in by pressing back button, the fragment looks overllaping previous content (child fragment).
This is the normal view:
This is the screenshot of overlapping view (when I resume the fragment):
You can get the difference as the second one's text is more deep (that means child fragment is overlapping)
How can I avoid that? This the code for my nested fragment:
public class CompetitiveProgramming extends SherlockProgressFragment implements
OnChapterSelectListener, OnSubChapterSelectListener {
View mContentView;
static public List<Chapter> chapterList = new ArrayList<Chapter>();
private ProcessTask processTask = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContentView = inflater.inflate(
R.layout.competitive_programming_exercise, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setContentShown(false);
setContentView(mContentView);
processTask = new ProcessTask();
processTask.execute();
}
protected class ProcessTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// background task
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
if (mContentView.findViewById(R.id.fragment_container) != null) {
getChildFragmentManager().beginTransaction()
.add(R.id.fragment_container, new ChaptersListFragment()).commit();
} else {
transaction.add(R.id.category_fragment, new ChaptersListFragment());
transaction.add(R.id.sub_category_fragment, new SubChaptersListFragment());
transaction.add(R.id.sub_sub_category_fragment,
new SubSubChaptersListFragment());
}
transaction.commit();
setContentShown(true);
}
}
static protected class Chapter {
String chapterTitle;
List<SubChapter> subchapterList;
public Chapter(String chapterTitle, List<SubChapter> subchapterList) {
this.chapterTitle = chapterTitle;
this.subchapterList = subchapterList;
}
}
#Override
public void onChapterSelected(int position) {
SubChaptersListFragment subChaptersListFrag = (SubChaptersListFragment) getChildFragmentManager()
.findFragmentById(R.id.sub_category_fragment);
if (subChaptersListFrag != null) {
subChaptersListFrag.updateList(position);
} else {
SubChaptersListFragment subChapterFragment = new SubChaptersListFragment();
Bundle args = new Bundle();
args.putInt(SubChaptersListFragment.CHAPTER_POSITION, position);
subChapterFragment.setArguments(args);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_container, subChapterFragment);
// transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onSubChapterSelected(int prev, int position) {
SubSubChaptersListFragment subSubChaptersListFrag = (SubSubChaptersListFragment) getChildFragmentManager()
.findFragmentById(R.id.sub_sub_category_fragment);
if (subSubChaptersListFrag != null) {
subSubChaptersListFrag.updateList(prev, position);
} else {
SubSubChaptersListFragment subSubChapterFragment = new SubSubChaptersListFragment();
Bundle args = new Bundle();
args.putIntArray(SubSubChaptersListFragment.POSITIONS, new int[]{prev, position});
subSubChapterFragment.setArguments(args);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_container, subSubChapterFragment);
// transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onStop() {
super.onStop();
if (processTask != null && processTask.getStatus() != AsyncTask.Status.FINISHED) {
processTask.cancel(true);
}
}
}

Kirill Kulakov is right. replace instead of add should be used. I edited the code:
public class CompetitiveProgramming extends SherlockProgressFragment implements
OnChapterSelectListener, OnSubChapterSelectListener {
View mContentView;
static public List<Chapter> chapterList = new ArrayList<Chapter>();
private ProcessTask processTask = null;
Fragment chapterFragment = null;
Fragment subChapterFragment = null;
Fragment subSubChapterFragment = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContentView = inflater.inflate(
R.layout.competitive_programming_exercise, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setContentShown(false);
setContentView(mContentView);
processTask = new ProcessTask();
processTask.execute();
}
protected class ProcessTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// background task
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
chapterFragment = new ChaptersListFragment();
if (mContentView.findViewById(R.id.fragment_container) != null) {
transaction.replace(R.id.fragment_container, chapterFragment);
} else {
subChapterFragment = new SubChaptersListFragment();
subSubChapterFragment = new SubSubChaptersListFragment();
transaction.replace(R.id.category_fragment, chapterFragment);
transaction.replace(R.id.sub_category_fragment, subChapterFragment);
transaction.replace(R.id.sub_sub_category_fragment, subSubChapterFragment);
}
transaction.commit();
setContentShown(true);
}
}
static protected class Chapter {
String chapterTitle;
List<SubChapter> subchapterList;
public Chapter(String chapterTitle, List<SubChapter> subchapterList) {
this.chapterTitle = chapterTitle;
this.subchapterList = subchapterList;
}
}
#Override
public void onChapterSelected(int position) {
SubChaptersListFragment subChaptersListFrag = (SubChaptersListFragment) getChildFragmentManager()
.findFragmentById(R.id.sub_category_fragment);
if (subChaptersListFrag != null) {
subChaptersListFrag.updateList(position);
} else {
SubChaptersListFragment subChapterFragment = new SubChaptersListFragment();
Bundle args = new Bundle();
args.putInt(SubChaptersListFragment.CHAPTER_POSITION, position);
subChapterFragment.setArguments(args);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_container, subChapterFragment);
// transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onSubChapterSelected(int prev, int position) {
SubSubChaptersListFragment subSubChaptersListFrag = (SubSubChaptersListFragment) getChildFragmentManager()
.findFragmentById(R.id.sub_sub_category_fragment);
if (subSubChaptersListFrag != null) {
subSubChaptersListFrag.updateList(prev, position);
} else {
SubSubChaptersListFragment subSubChapterFragment = new SubSubChaptersListFragment();
Bundle args = new Bundle();
args.putIntArray(SubSubChaptersListFragment.POSITIONS, new int[]{prev, position});
subSubChapterFragment.setArguments(args);
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_container, subSubChapterFragment);
// transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onStop() {
super.onStop();
if (processTask != null && processTask.getStatus() != AsyncTask.Status.FINISHED) {
processTask.cancel(true);
}
}
}
Hope this would help!

You probably are adding the fragment in your onResume(), which is not what you want as each time you are resumed new fragment is added. Just fix your code's logic

Related

all Fragment recreating when a switching through fragments using tablayout

I am creating an application which is based on Tabs using tablayout. I didn't use viewpager. My logic is that users can create fragments (Tabs) like adding tabs in chrome so that whenever user clicks add button a new tab is created with a fragment. Now i need to save unique time stamp of each fragment created time in shared preference so that whenever i move to one fragment i can use that shared reference timestamp value to do unique function intended for that particular fragment.
But i don't know where to save that timestamp. I tried to get the time in milliseconds in Oncreate function of Fragment but whenever I switch between tabs everytime the onCreate call so that each time i switch between tabs the shared preference value changes as i added it in onCreate in Fragments.
My Logic is that it should only create once a fragment is created when user clicks add and must be able to use that in fragments.
As every time i switch to other fragement it just reinitilize all view and onCreate in called. so i could not set timestamp in oncreate..
Please help me
my Activity code is:
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
getAllWidgets();
bindWidgetsWithAnEvent();
setupTabLayout();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
allTabs.addTab(allTabs.newTab().setText("ONE"),true);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
allTabs.addTab(allTabs.newTab().setText("NEW_TAB"),true);
bindWidgetsWithAnEvent();
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setCurrentTabFragment(int tabPosition)
{
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild();
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
public void replaceFragment(Fragment fragment, String fragmentName) {
long time= System.currentTimeMillis();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
public void backStackFragment(Fragment fragment, String fragmentName) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
ft.addToBackStack(null);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
FragmentChild class:
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
PreferenceHelper prefs;
private TabLayout tabLayout;
private ViewPagerAdapter adapter;
public static ViewPager viewPager;
String posid = "";
int page =0;
String title = "";
TabLayout allTabs;
int tab_position = 0;
long time=0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//GlobalBus.getBus().register(this);
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
Log.e("onCreateView","onCreateView");
getIDs(view);
setEvents();
return view;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
time= System.currentTimeMillis();
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
Log.e("onCreate","onCreate");
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.e("onViewCreated","onViewCreated");
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
EventBus.getDefault().unregister(this);
}
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentFirst = new FragmentChild();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
allTabs = (TabLayout) getActivity().findViewById(R.id.simpleTabLayout);
mGridView = (GridView) getView().findViewById(R.id.gridView);
prefs = new PreferenceHelper(getActivity());
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
}
#Override
public void onStart() {
super.onStart();
Log.e("onStart","onStart");
EventBus.getDefault().register(this);
tab_position=allTabs.getSelectedTabPosition();
//Log.e("TAB ID",String.valueOf(tab_position));
prefs.save(String.valueOf(tab_position),"tab-"+time);
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
fetchProducts(tab_position);
}
}
#Override
public void onResume() {
super.onResume();
Log.e("onResume","onResume");
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
Log.e("onPause","onPause");
super.onPause();
}
#Subscribe
public void onEvent(GlobalBus event){
posid = event.getMessage();
//Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}
public void fetchProducts(int tabPosition){
String tabid = prefs.getString(String.valueOf(tabPosition),"0");
Fragment fragment = getFragmentManager().findFragmentById(R.id.simpleFrameLayout);
String tag = (String) fragment.getTag();
//Log.e("URL","http://35.184.41.163/phpmyadmin/app/demo/products.php?tabid="+tabid+"&tab_position="+tabPosition);
RestClientHelper.getInstance().get("http://35.184.41.163/phpmyadmin/app/demo/products.php", new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
mGridData.clear();
mGridAdapter.setGridData(mGridData);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
UPDATE as suggested by #Larry Hsiao
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
PreferenceHelper prefs;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
private final List<Fragment> fragments = new ArrayList<>(); // maintain the instance for switching
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
prefs = new PreferenceHelper(TabActivity.this);
getAllWidgets();
//bindWidgetsWithAnEvent();
setupTabLayout();
bindWidgetsWithAnEvent();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
add.performClick();
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
int locfirst = allTabs.getSelectedTabPosition();
locfirst = locfirst+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+locfirst),true);
/*long time= System.currentTimeMillis();
prefs.save("tab_"+locfirst,"tab_"+time);*/
fragments.add(newFragment(0));
addFragment(fragments.get(0));
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int loc = allTabs.getSelectedTabPosition();
loc = loc+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+loc),true);
fragments.add(newFragment(loc));
addFragment(fragments.get(loc));
/*bindWidgetsWithAnEvent();
long time= System.currentTimeMillis();
prefs.save("tab_"+loc,"tab_"+time);*/
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentChild();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.simpleFrameLayout, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
}else {
transaction.add(R.id.simpleFrameLayout,fragment);
}
transaction.commit();
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = (currentIndex + 1) % 2; // only two fragment switching
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
//setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
\
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
This force closes with this error:
FATAL EXCEPTION: main
Process: com.eazypos.app, PID: 13624
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.eazypos.app.TabActivity$3.onTabSelected(TabActivity.java:115)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:483)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:465)
at com.eazypos.app.TabActivity$1.onClick(TabActivity.java:62)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
REMOVE TAB FUNCTION
public void removeTab(int position) {
Toast.makeText(getActivity(), "REMOVING --> "+position, Toast.LENGTH_SHORT).show();
prefs.remove("tab_"+position);
if (allTabs.getChildCount() > 0) {
allTabs.removeTabAt(position);
}
}
To save the value only once.. in timeStamp in the shared prefs just use this in each fragment..
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getActivity() == null)
{
// generate time stamp in miliseconds as you are doing
// and save it in shared prefs
// this will be called only once..
}
}
OR YOU CAN TRY IN :-
UPDATE onCreate of fragmentChild
time= System.currentTimeMillis();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("My_prefs_name",Context.MODE_PRIVATE);
String timeStamp = sharedPreferences.getString("timeStamp","");
if ( timeStamp.isEmpty())
{
// SAVE TIME IN SHAREPREFS
sharedPreferences.edit().putString("timeStamp",time).apply();
}
You should maintain the Fragment instance which you already create. (With FragmentManager or just keep it with variable might do the job)
The method setCurrentTabFragment() in Activity which creating new Fragment is invoked every time user click tab. As the result, fragment always run through the onCreate()
// this method invoke every time user click the tab
private void setCurrentTabFragment(int tabPosition){
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild(); // creating new Fragment
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
Edited:
Use List to maintain the Fragment instance we already create.
Switch Fragment with hide()/show() provided by FragmentManager, using add() if the Fragment not added to FragmentManager before.
Sample Code:
public class MainActivity extends AppCompatActivity {
private final List<Fragment> fragments = new ArrayList<>();
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tabLayout = findViewById(R.id.tabLayout);
// initial with one page
Fragment firstFragment = newFragment(0);
fragments.add(firstFragment);
addFragment(firstFragment);
tabLayout.addTab(tabLayout.newTab().setText("Initial tab"));
// user events
findViewById(R.id.main_createTab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragments.add(newFragment(tabLayout.getTabCount()));
tabLayout.addTab(tabLayout.newTab().setText("Pages " + tabLayout.getTabCount()));
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = tab.getPosition();
if (currentIndex == nextPageIndex){
return;
}
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
}
#Override public void onTabUnselected(TabLayout.Tab tab) {}
#Override public void onTabReselected(TabLayout.Tab tab) {}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentWithLog();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.main_fragmentFrame, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
} else {
transaction.add(R.id.main_fragmentFrame, fragment);
}
transaction.commit();
}
}

After two different fragments have been replaced, first fragment is recreated when on pressed back button

I have three fragment and one activity. It works this way:
[activity]-> [MainFragment]->[MenuFragment]->[SignUpFragment]
When [SignUpFragment] is back pressed, the [MainFragment] is created twice.
I tried setRetaInInstance(true) and I checked savedInstanceState but I can not prevent [MainFragment] recreating.
This is my MainActivity:
public class MainActivity extends AppCompatActivity {
public Bundle mSavedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedInstanceState = savedInstanceState;
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
callMainFragment();
}
private void callMainFragment() {
if (mSavedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MainFragment(), MainFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
public ActionBar getMainActionBar(){
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Action Bar Display settings
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// Custom view inflater
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Custom layout view
View viewActionBar = inflater.inflate(R.layout.action_bar, null);
// Set custom view
actionBar.setCustomView(viewActionBar);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
}
return actionBar;
}
This is my MainFragment:
public class MainFragment extends BaseFragment implements AdapterView.OnItemClickListener, BuyersGuideCategoriesDelegate, View.OnClickListener {
private Bundle mSavedInstanceState;
private BuyersGuideCategoriesFragment mCategoriesFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (mSavedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_main, container, false);
// Call Grid View Buyers Guide Fragment
mCategoriesFragment = new BuyersGuideCategoriesFragment();
mCategoriesFragment.mGridViewDelegate = this;
setIcons();
setTitles();
setTexts();
initListView();
}
return mView;
}
#Override
public void onResume() {
super.onResume();
ImageView menu = (ImageView) ((MainActivity) getActivity()).getMainActionBar().getCustomView().findViewById(R.id.action_bar_menu_icon);
menu.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mSavedInstanceState == null) {
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MenuFragment(),MenuFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
}
This is my MenuFragment:
public class MenuFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private Bundle mSavedInstanceState;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_menu, container, false);
setMenuItemsListViewAdapter();
}
return mView;
}
private void setMenuItemsListViewAdapter() {
ListView menuItems = (ListView) mView.findViewById(R.id.list_menu_items);
ListMenuItemsListViewAdapter adapter = new ListMenuItemsListViewAdapter(getContext(),getMenuItemNames());
menuItems.setAdapter(adapter);
menuItems.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch ((String) parent.getAdapter().getItem(position)){
case SIGN_UP:
replaceFragment(R.id.container_category,new SignUpFragment(),SignUpFragment.class.getSimpleName());
break;
}
}
private void replaceFragment(int containerId,Fragment fragment, String fragmentTag){
if (mSavedInstanceState == null){
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(containerId,fragment,fragmentTag);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.menu_back_icon:
replaceFragment(R.id.container_category, new MainFragment(),MainFragment.class.getSimpleName());
break;
}
}
}
And this is my SignUpFragment:
public class SignUpFragment extends BaseFragment implements View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_sign_up, container, false);
}
return mView;
}
}
EDIT 1: The MainFragment is recreated only when I return from SignUpFragment to MenuFragment. I am doing wrong using so many fragments? Should I use activity?
When you are move between Fragments, call addToBackStack() :
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace( R.id.fragment, new MyFragment() ).addToBackStack( "ftransaction" ).commit();
Create first Fragment:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.add(R.id.container, new FirstFragment()).addToBackStack(null).commit();
Second:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new SecondFragment()).addToBackStack(null).commit();
and Third:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new ThirdFragment()).commit();

How to save loaded listView state in fragment?

I have one activity, fragment with listView and fragment with details for each listView item. I am getting fragments data from API. How should I save loaded date and listView position correctly to be able to restore it when I am returning back to the listView?
I tried to implement this solution Once for all, how to correctly save instance state of Fragments in back stack? but I cannot restore my listView correctly.
My MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
listFragment = new ListFragment();
fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, listFragment);
fragmentTransaction.commit();
if (savedInstanceState != null) {
//Restore the fragment's instance
listFragment = (ListFragment)getSupportFragmentManager().getFragment(savedInstanceState, "listContent");
}
...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "listContent", listFragment);
}
and ListFragment
public class ListFragment extends Fragment {
public static final String REQUEST_TAG = "ProjectListFragment";
private int page;
private View view;
private RelativeLayout loading ;
private PagingListView listView;
private PagingProjectListAdapter adapter;
private ArrayList<String> projects = new ArrayList<>();
private ArrayList<String> loadedProjects = new ArrayList<>();
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_list, container, false);
listView = (PagingListView) view.findViewById(R.id.projectsListView);
loading = (RelativeLayout) view.findViewById(R.id.loading);
//page = 1;
adapter = new PagingProjectListAdapter(getContext(), ListFragment.this);
listView.setAdapter(adapter);
listView.setHasMoreItems(true);
// Inflate the layout for this fragment
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// FIXME not used
listView.onFinishLoading(true, projects);
//Restore the fragment's state here
} else {
projects.clear();
page = 1;
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
new CustomVolleyAsyncTask().execute();
}
});
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentPosition", 0);
//Save the fragment's state here
}
public void itemClickMethod(View detailsView) {
LinearLayout linearLayout = (LinearLayout) detailsView;
String bid = linearLayout.getContentDescription().toString();
Bundle bundle = new Bundle();
String k = "ProjectID";
bundle.putString(k, bid);
DetailsFragment detailsFragment = new DetailsFragment();
detailsFragment.setArguments(bundle);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, detailsFragment, "DetailsFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
private class CustomVolleyAsyncTask extends SafeAsyncTask<List<String>> implements Response.Listener,
Response.ErrorListener {
public List<String> status = null;
private RequestQueue mQueue;
#Override
public List<String> call() throws Exception {
mQueue = CustomVolleyRequestQueue.getInstance(view.getContext())
.getRequestQueue();
String url = "http://www.myapi.com/api/v1/data/" + Integer.toString(page);
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
// TODO rm redundant result
return status;
}
#Override
public void onErrorResponse(VolleyError error) {
// FIXME check no response case crash
//mTextView.setText(error.getMessage());
}
#Override
public void onResponse(Object response) {
try {
JSONArray projectsJSON = new JSONArray(((JSONObject) response).getString("projects"));
loadedProjects.clear();
for (int i=0; i < projectsJSON.length(); i++) {
loadedProjects.add(projectsJSON.getJSONObject(i).toString());
}
page++;
listView.onFinishLoading(true, loadedProjects);
if (loading.getVisibility() == View.VISIBLE && !listView.isLoading()){
listView.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}}}
}
currently, my savedInstanceState is always null, what am I missing?
I think, that your fragment created twice, when configuration changed. Here Staffan explain, why this happend. I resolve similar problem by this way (in activity onCreate):
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(TAG);
if(fragment==null)
fragmentManager.beginTransaction()
.add(R.id.container, NewsFragment.newInstance(),TAG)
.commit();

Fragment implements AbsListView.OnItemClickListener with ArrayAdapter ==> onItemClick Listener is null

My implementation of an AbsListView.OnItemClickListener in a Fragment performs no action and displays no error, when a list item is tapped.
I read the documentation, searched Google & SOF and read the SDK source, but could not solve the problem.
The Activity:
public class VenueActivity extends Activity implements
NBVenuesFragment.OnFragmentInteractionListener,
NBFriendsFragment.OnFragmentInteractionListener,
UploadedPhotosFragment.OnFragmentInteractionListener {
private static final String TAB_KEY_INDEX = "tab_key";
private static final String TAG = "VenueActivity";
private Fragment mCurrentFragment = null;
private Fragment mNewFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_venue);
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab mVenuesFragmentTab = actionbar.newTab().setText(
getString(R.string.ui_nearby_venues_tab));
ActionBar.Tab mNBFriendsFragmentTab = actionbar.newTab().setText(
getString(R.string.ui_nearby_friends_tab));
ActionBar.Tab mUploadedPhotosFragmentTab = actionbar.newTab().setText("Photos Uploaded");
Fragment mVenuesFragment = new NBVenuesFragment();
Fragment mNBFriendsFragment = new NBFriendsFragment();
Fragment mUploadedPhotosFragment = new UploadedPhotosFragment();
mVenuesFragmentTab.setTabListener(new VenueTabsListener(mVenuesFragment,
getApplicationContext()));
mNBFriendsFragmentTab.setTabListener(new VenueTabsListener(mNBFriendsFragment,
getApplicationContext()));
mUploadedPhotosFragmentTab.setTabListener(new VenueTabsListener(mUploadedPhotosFragment,
getApplicationContext()));
actionbar.addTab(mVenuesFragmentTab);
//actionbar.addTab(mNBFriendsFragmentTab);
actionbar.addTab(mUploadedPhotosFragmentTab);
if (savedInstanceState != null) {
actionbar.setSelectedNavigationItem(savedInstanceState.getInt(
TAB_KEY_INDEX, 0));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.venue_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_check_in:
Toast.makeText(this, getString(R.string.action_check_in),
Toast.LENGTH_SHORT).show();
return true;
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.onBackPressed();
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(TAB_KEY_INDEX, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public void onNearByVenueSelection(VenuesDummyData.VenuesDummyItem venueData){
Bundle args = new Bundle();
args.putString("VENUE_ID", venueData.venueId);
args.putString("VENUE_NAME", venueData.venueName);
args.putString("VENUE_ADDRESS", venueData.venueAddress);
args.putString("VENUE_CHECK_INS", venueData.venueCheckIns);
args.putString("VENUE_LIKES", venueData.venueLikes);
args.putString("VENUE_CHECK_INS_FLIRT", venueData.venueCheckInsflirt);
args.putString("VENUE_CHECK_INS_FRIENDS", venueData.venueCheckInsFriends);
args.putString("OMEGA", venueData.omega);
Fragment mVenueDetailsFragment = new VenueDetailsFragment();
mVenueDetailsFragment.setArguments(args);
mCurrentFragment = new NBVenuesFragment();
mNewFragment = mVenueDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mVenueDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mVenueDetailsFragment, tag);
ft.commit();
}
#Override
public void onNearByFriendSelection(JsonObject mUserInfo){
Bundle args = new Bundle();
args.putString("FRIEND_NAME", mUserInfo.get("name").getAsString());
//args.putString("FRIEND_ID", mUserInfo.friendId);
args.putString("FRIEND_PHOTO", mUserInfo.get("photo_url").getAsString());
//args.putString("VENUE_ID", mUserInfo.venueId);
//args.putString("VENUE_NAME", mUserInfo.venueName);
Fragment mFriendDetailsFragment = new FriendDetailsFragment();
mFriendDetailsFragment.setArguments(args);
mCurrentFragment = new NBFriendsFragment();
mNewFragment = mFriendDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mFriendDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mFriendDetailsFragment, tag);
//ft.addToBackStack(tag);
ft.commit();
}
#Override
public void onUserSelection(JsonObject mUserInfo){
Log.i(TAG, "onUserSelection");
Log.i(TAG, "mUserInfo ==> " + mUserInfo.toString());
Bundle args = new Bundle();
args.putString("USER_NAME", mUserInfo.get("name").getAsString());
//args.putString("FRIEND_ID", mUserInfo.friendId);
args.putString("USER_PHOTO", mUserInfo.get("photo_url").getAsString());
//args.putString("VENUE_ID", mUserInfo.venueId);
//args.putString("VENUE_NAME", mUserInfo.venueName);
Fragment mUserDetailsFragment = new UserDetailsFragment();
mUserDetailsFragment.setArguments(args);
mCurrentFragment = new UploadedPhotosFragment();
mNewFragment = mUserDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mUserDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mUserDetailsFragment, tag);
//ft.addToBackStack(tag);
ft.commit();
}
#Override
public void onBackPressed() {
if (mCurrentFragment != null && mNewFragment != null) {
String tag = mCurrentFragment.getTag();
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.remove(mNewFragment);
ft.replace(R.id.fragment_container, mCurrentFragment, tag);
ft.commit();
mCurrentFragment = null;
mNewFragment = null;
} else {
super.onBackPressed();
}
}
}
class VenueTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public VenueTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
}
The list Fragment:
public class UploadedPhotosFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
private AbsListView mListView;
private JsonObject mUserInfo;
private PhotosAdapter mAdapter;
private JsonArray mDataFromServer;
private String TAG = "UploadedPhotosFragment";
private void getPhotosData() {
Log.i(TAG, "getPhotosData");
AsyncTask<Void, Void, FlefuApiMessagesGetPhotosResponseMessage> photosJsonString;
photosJsonString = new GetPhotos() {
#Override
protected void onPostExecute(FlefuApiMessagesGetPhotosResponseMessage response) {
Log.i(TAG, "#overridden GetPhotos onPostExecute: " + response.getData());
mDataFromServer = (JsonArray)new JsonParser().parse(response.getData());
mUserInfo = new JsonObject();
for (int i = 0; i < mDataFromServer.size(); i++) {
mUserInfo = mDataFromServer.get(i).getAsJsonObject();
mAdapter.add(mUserInfo);
}
}
};
photosJsonString.execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPhotosData();
mAdapter = new PhotosAdapter(getActivity());
Log.i(TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_photo_image, container, false);
//int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
mListView = (AbsListView) view.findViewById(R.id.photos);
//mListView.setNumColumns(3);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private class PhotosAdapter extends ArrayAdapter <JsonObject> {
private LayoutInflater inflater;
private class ViewHolder {
TextView name;
//TextView venue;
ImageView thumb;
}
public PhotosAdapter(Context context) {
super(context, R.layout.uploaded_image);
Log.i(TAG, context.toString());
inflater = LayoutInflater.from(context);
Log.i(TAG, "PhotosAdapter");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView");
ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.uploaded_image, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.thumb = (ImageView) convertView.findViewById(R.id.image);
//holder.venueName = (TextView) convertView.findViewById(R.id.venueName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// select the image view
Ion.with(holder.thumb)
.resize(300, 300)
.centerCrop()
//.placeholder(R.drawable.placeholder)
//.error(R.drawable.error)
.load(getItem(position).get("thumb_url").getAsString());
holder.name.setText(getItem(position).get("name").getAsString());
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "parent ==> " + parent.toString());
Log.i(TAG, "view ==> " + view.toString());
if (mListener != null) {
Log.i(TAG, "call to onUserSelection ==> " +
mDataFromServer.get(position).getAsJsonObject().toString());
mListener.onUserSelection(mDataFromServer.get(position).getAsJsonObject());
}
}
public interface OnFragmentInteractionListener {
public void onUserSelection(JsonObject mUserInfo);
}
}
You did not initialized Your mListener value. Your mListener is null and nothing happens when You click a ListView item.

How could I get view of one fragment while add this fragment to an Activity

I have one FragmentActivity and a Fragment, well, now I want to add this fragment to the Activity programmatically, and I also want to update value of one TextView. but I keep getting NullPointException.
Need some help here... :(
this is my code:
public class NewsDetailsFragment extends Fragment {
private View _currentview = null;
public View getCurrentView() {
return _currentview;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
_currentview = inflater.inflate(R.layout.newsdetails_layout, container,
false);
Button b = (Button) _currentview.findViewById(R.id.btnReplace);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
transaction.replace(R.id.landscapeLayout,
new ReplacementFragment(), "replace");
} else {
transaction.replace(R.id.newsdetailsPortrait,
new ReplacementFragment(), "replace");
}
transaction.addToBackStack(null);
transaction.commit();
}
});
return _currentview;
}
public void setNewsContent(String content) {
TextView lblNewsContent = (TextView) getView().findViewById(
R.id.lblNewsContent);
lblNewsContent.setText(content);
lblNewsContent.setTextColor(Color.CYAN);
}
}
This is the FragmentActivity:
public class NewsDetailsActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdetailsactivity_layout);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
// setContentView(R.layout.newsdetails_layout);
NewsDetailsFragment detailsFragment = new NewsDetailsFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.newsdetailsPortrait, detailsFragment,
"newsdatails");
String newString = getIntent().getStringExtra("news");
if (null != newString) {
TextView t = (TextView) detailsFragment.getView().findViewById(
R.id.lblNewsContent);
t.setText(newString);
t.setTextColor(Color.GREEN);
}
transaction.commit();
}
}
Thanks in advance! :)

Categories

Resources