How to draw a layout inside layout - java

I have aplication where after clicking on Statistics i call StatsFragment. StatsFragment uses fragment_stats xml layout that has there a TabLayout and CustomViewPager. However when i clicked on Statistics so my StatsFragment is called data are not drawn there. After i click on some tab data will be there.
Problem is with initial drawing. From How can you tell when a layout has been drawn? i know i shall use somehow ViewTreeObserver but cant find the way where and how.
fragment_stats xml file:
<RelativeLayout 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"
tools:context=".StatsFragment">
<!-- TODO: Update blank fragment layout -->
<!--android:elevation="6dp"-->
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<pv239.fi.muni.cz.moneymanager.CustomViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"
>
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</pv239.fi.muni.cz.moneymanager.CustomViewPager>
</RelativeLayout>
tab_fragment xml file:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/gridViewScreenStats">
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/graph" />
<GridLayout
android:id="#+id/stats"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/graph"
android:layout_gravity="center"
android:background="#drawable/box"
android:layout_margin="10dp"
android:rowCount="5"
android:columnCount="2"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Starting balance: "
android:paddingLeft="10dp"
android:id="#+id/startBalanceLabel"
android:layout_row="0"
android:layout_column="0"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/startBalanceLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/startBalance"
android:layout_row="0"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/startBalance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Ending balance: "
android:paddingLeft="10dp"
android:id="#+id/endBalanceLabel"
android:layout_row="1"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/startBalance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:layout_toRightOf="#id/endBalanceLabel"
android:id="#+id/endBalance"
android:layout_row="1"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Incomes: "
android:layout_below="#id/endBalanceLabel"
android:id="#+id/incomeStats"
android:layout_row="2"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:textColor="#color/recordPositiveValue"
android:id="#+id/incomeSumStats"
android:layout_below="#id/endBalance"
android:textAlignment="textEnd"
android:layout_row="2"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Expenses:"
android:id="#+id/expenseStats"
android:layout_row="3"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:textColor="#color/recordNegativeValue"
android:id="#+id/expenseSumStats"
android:textAlignment="textEnd"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="+/- status:"
android:id="#+id/actualStats"
android:layout_row="4"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/actualSumStats"
android:textColor="#color/recordPositiveValue"
android:textAlignment="textEnd"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_row="4"
android:layout_column="1" />
</GridLayout>
<!-- Income records -->
<ListView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#drawable/box"
android:layout_below="#id/stats"
android:layout_margin="10dp"
android:id="#+id/listViewIncomeStats"
android:nestedScrollingEnabled="true"/>
<!-- Expenses records -->
<ListView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#drawable/box"
android:layout_below="#+id/listViewIncomeStats"
android:layout_margin="10dp"
android:id="#+id/listViewExpences"
android:nestedScrollingEnabled="true"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
StatsFragment java file:
public class StatsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView incomeListView;
private ListView expensesListView;
private OnStatsInteractionListener mListener;
public StatsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment StatsFragment.
*/
// TODO: Rename and change types and number of parameters
public static StatsFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
StatsFragment fragment = new StatsFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_stats, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) getView().findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
// TextView txt = (TextView) (adapter.getItem(tab.getPosition())).getView().findViewById(R.id.startMonthStats);
processChanges((adapter.getItem(tab.getPosition())).getView(),tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onStatsInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnStatsInteractionListener {
// TODO: Update argument type and name
void onStatsInteraction(Uri uri);
}
private Date numbersToDate(int daysBack, int monthsBack, int yearsBack)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, daysBack *(-1));
cal.add(Calendar.MONTH, monthsBack *(-1));
cal.add(Calendar.YEAR, yearsBack *(-1));
return cal.getTime();
}
public void processChanges(View tabView, int tabNum)
{
int d =7;
int m =0;
int y =0;
MMDatabaseHelper sloh = MMDatabaseHelper.getInstance(getActivity());
if (tabNum == 1)
{
d =0;
m =1;
y =0;
}
else if (tabNum == 2)
{
d =0;
m =0;
y =1;
}
createGraph(tabView, d, m, y, sloh);
setBalances(tabView, d, m, y, sloh);
setListValues(tabView, d, m, y, sloh);
}
private void setListValues(View tabView, int d, int m, int y,MMDatabaseHelper sloh) {
// Creating incomes list
incomeListView = (ListView) tabView.findViewById(R.id.listViewIncomeStats);
Cursor incomeRecords = sloh.getRecordsInRange(">",d,m,y);
RecordsDbToStatsAdapter incomeAdapter = new RecordsDbToStatsAdapter(this.getContext(), incomeRecords, 0);
incomeListView.setAdapter(incomeAdapter);
// Creating expenses list
expensesListView = (ListView) tabView.findViewById(R.id.listViewExpences);
Cursor expensesRecords = sloh.getRecordsInRange("<",d,m,y);
RecordsDbToStatsAdapter expensesAdapter = new RecordsDbToStatsAdapter(this.getContext(), expensesRecords, 0);
expensesListView.setAdapter(expensesAdapter);
}
private void setBalances(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
//Fetching Values of incomes and expenses and balances
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setMaximumFractionDigits(2);
TextView incSum = (TextView) tabView.findViewById(R.id.incomeSumStats);
Integer helpInc = sloh.getSumRecordsInRange(">",d,m,y);
BigDecimal incValue = new BigDecimal(helpInc.toString());
incSum.setText(format.format(incValue.abs().setScale(2).doubleValue()));
TextView expSum = (TextView) tabView.findViewById(R.id.expenseSumStats);
Integer helpExp = sloh.getSumRecordsInRange("<",d,m,y);
BigDecimal expValue = new BigDecimal(helpExp.toString());
expSum.setText(format.format(expValue.abs().setScale(2).doubleValue()));
TextView startBal = (TextView) tabView.findViewById(R.id.startBalance);
BigDecimal startValue = new BigDecimal(sloh.getStartingBal(numbersToDate(d,m,y)).toString());
startBal.setText(format.format(startValue.abs().setScale(2).doubleValue()));
TextView endBal = (TextView) tabView.findViewById(R.id.endBalance);
BigDecimal endValue = new BigDecimal(sloh.getEndingBal().toString());
endBal.setText(format.format(endValue.abs().setScale(2).doubleValue()));
TextView actState = (TextView) tabView.findViewById(R.id.actualSumStats);
actState.setText(format.format(new BigDecimal(helpInc + helpExp).setScale(2).doubleValue()));
}
private void createGraph(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
// Graph rendering section
// Cursor graphCursor = sloh.getRecordsInRange(null,d,m,y);
// graphCursor.moveToFirst();
int days=0;
if (d == 7) { days = d;}
if (m == 1) { days = 28;}
if (y == 1) { days = 365;}
ArrayList numList = new ArrayList();
GraphView graph = (GraphView) tabView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] { });
Calendar day = Calendar.getInstance();
day.set(Calendar.HOUR_OF_DAY,0);
day.set(Calendar.MINUTE,0);
day.set(Calendar.SECOND,0);
for(int i=days; i>0;i--) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR,-i);
day.setTime(cal.getTime());
Log.i("TIME",cal.getTime().toString());
numList.add(sloh.getCurrentBalanceForOneDay(cal.getTime()));
series.appendData(new DataPoint(day.getTime(),sloh.getCurrentBalanceForOneDay(cal.getTime())),true,days);
}
Log.i("Pole", numList.toString());
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(getActivity()));
graph.getGridLabelRenderer().setNumHorizontalLabels(4); // only 4 because of the space
graph.addSeries(series);
}
}

From what I can tell, you're not doing the right things at the right time.
When the onCreateView of your fragment is called, you inflate the corresponding layout but do not set any value in there.
Simply swapping all the code you have in onActivityCreated into the onCreateView should do the trick, as follow :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) layout.findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
processChanges((adapter.getItem(tab.getPosition())).getView(),tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return (layout);
}
EDIT : After having a second (and closer) look at your code, the best idea would be to have fragments managing your tabs, so that you could put your logic in there (and place them in each tab). To do so :
Step 1 : Create a new fragment class for your pages
public abstract class PageFragment extends Fragment {
private int pageNumber;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt("page_number", page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return (fragment);
}
public PageFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pageNumber = getArguments().getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.tab_fragment, container, false);
//Get all the views you need for your page, using
//layout.findViewById();
//Then you will need to call processChanges for that page
processChanges(layout, pageNumber);
return (layout);
}
//Also add here all the logic associated with processChanges
}
Step 2 will be to get references of your fragments in your StatsFragment, and add these fragments to your pager :
private PageFragment pageOne;
private PageFragment pageTwo;
private PageFragment pageThree;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
pageOne = PageFragment.newInstance(0);
pageTwo = PageFragment.newInstance(1);
pageThree = PageFragment.newInstance(2);
tabLayout.addFragment(pageOne, "7 days");
tabLayout.addFragment(pageTwo, "1 month");
tabLayout.addFragment(pageThree, "1 year");
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}
Step 3 : You will finally need to have a custom pager adapter to hold the titles and the fragments of your pager :
public class MyViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mTitles = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return (mFragments.get(position));
}
#Override
public int getCount() {
return (mFragments.size());
}
#Override
public String getPageTitle(int position) {
return (mTitles.get(position));
}
}
To use it, simply create it via (instead of your PagerAdapter)
final MyPagerAdapter adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());

According to Nsimon i update current state. This solved problem with initial screen for me. Big thank to NSimon.
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return (mFragments.get(position));
}
#Override
public int getCount() {
return (mFragments.size());
}
#Override
public String getPageTitle(int position) {
return (mTitles.get(position));
}
}
PageFragment:
public class PageFragment extends Fragment {
private int pageNumber;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt("page_number", page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return (fragment);
}
public PageFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pageNumber = getArguments().getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.tab_fragment, container, false);
//Get all the views you need for your page, using
//layout.findViewById();
//Then you will need to call processChanges for that page
processChanges(layout, pageNumber);
return (layout);
}
public void processChanges(View tabView, int tabNum)
{
int d =7;
int m =0;
int y =0;
MMDatabaseHelper sloh = MMDatabaseHelper.getInstance(getActivity());
if (tabNum == 1)
{
d =0;
m =1;
y =0;
}
else if (tabNum == 2)
{
d =0;
m =0;
y =1;
}
createGraph(tabView, d, m, y, sloh);
setBalances(tabView, d, m, y, sloh);
setListValues(tabView, d, m, y, sloh);
}
private void setListValues(View tabView, int d, int m, int y,MMDatabaseHelper sloh) {
// Creating incomes list
ListView incomeListView = (ListView) tabView.findViewById(R.id.listViewIncomeStats);
Cursor incomeRecords = sloh.getRecordsInRange(">",d,m,y);
RecordsDbToStatsAdapter incomeAdapter = new RecordsDbToStatsAdapter(this.getContext(), incomeRecords, 0);
incomeListView.setAdapter(incomeAdapter);
// Creating expenses list
ListView expensesListView = (ListView) tabView.findViewById(R.id.listViewExpences);
Cursor expensesRecords = sloh.getRecordsInRange("<",d,m,y);
RecordsDbToStatsAdapter expensesAdapter = new RecordsDbToStatsAdapter(this.getContext(), expensesRecords, 0);
expensesListView.setAdapter(expensesAdapter);
}
private Date numbersToDate(int daysBack, int monthsBack, int yearsBack)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, daysBack *(-1));
cal.add(Calendar.MONTH, monthsBack *(-1));
cal.add(Calendar.YEAR, yearsBack *(-1));
return cal.getTime();
}
private void setBalances(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
//Fetching Values of incomes and expenses and balances
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setMaximumFractionDigits(2);
TextView startBal = (TextView) tabView.findViewById(R.id.startBalance);
BigDecimal startValue = new BigDecimal(sloh.getStartingBal(numbersToDate(d,m,y)).toString());
startBal.setText(String.valueOf(startValue.setScale(2).doubleValue()));
TextView endBal = (TextView) tabView.findViewById(R.id.endBalance);
BigDecimal endValue = new BigDecimal(sloh.getEndingBal().toString());
endBal.setText(String.valueOf(endValue.setScale(2).doubleValue()));
TextView incSum = (TextView) tabView.findViewById(R.id.incomeSumStats);
Integer helpInc = sloh.getSumRecordsInRange(">",d,m,y);
BigDecimal incValue = new BigDecimal(helpInc.toString());
incSum.setText(String.valueOf(incValue.setScale(2).doubleValue()));
TextView expSum = (TextView) tabView.findViewById(R.id.expenseSumStats);
Integer helpExp = sloh.getSumRecordsInRange("<",d,m,y);
BigDecimal expValue = new BigDecimal(helpExp.toString());
expSum.setText(String.valueOf(expValue.setScale(2).doubleValue()));
}
private void createGraph(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
// Graph rendering section
// Cursor graphCursor = sloh.getRecordsInRange(null,d,m,y);
// graphCursor.moveToFirst();
int days=0;
if (d == 7) { days = d;}
if (m == 1) { days = 28;}
if (y == 1) { days = 365;}
ArrayList numList = new ArrayList();
GraphView graph = (GraphView) tabView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] { });
Calendar day = Calendar.getInstance();
day.set(Calendar.HOUR_OF_DAY,0);
day.set(Calendar.MINUTE,0);
day.set(Calendar.SECOND,0);
for(int i=days; i>0;i--) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR,-i);
day.setTime(cal.getTime());
Log.i("TIME",cal.getTime().toString());
numList.add(sloh.getCurrentBalanceForOneDay(cal.getTime()));
series.appendData(new DataPoint(day.getTime(),sloh.getCurrentBalanceForOneDay(cal.getTime())),true,days);
}
Log.i("Pole", numList.toString());
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(getActivity()));
graph.getGridLabelRenderer().setNumHorizontalLabels(4); // only 4 because of the space
graph.addSeries(series);
}
}
StatsFragment:
private PageFragment pageOne;
private PageFragment pageTwo;
private PageFragment pageThree;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
pageOne = PageFragment.newInstance(0);
pageTwo = PageFragment.newInstance(1);
pageThree = PageFragment.newInstance(2);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) layout.findViewById(R.id.pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(pageOne,"7 days");
adapter.addFragment(pageTwo,"1 month");
adapter.addFragment(pageThree,"1 year");
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return layout;
}

Related

how save value of checkbox after close the app in android?

I want save the state of checkbox after close the app
what I should to do?
I don't know how I do that with list view and arrayadapter
how use sharedpreferences here?
in MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
MyAdView.SetAd((AdView)findViewById(R.id.adView));
ListView list = (ListView) findViewById(R.id.list);
ArrayList<Word> worda = new ArrayList<>();
worda.add(new Word("The B",R.drawable.ic_launcher_background));
worda.add(new Word("The B",R.drawable.ic_launcher_background));
WordAdapter adapter = new WordAdapter(this, worda);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, TheBossBabyS1.class);
startActivity(intent);
}
} });
}
}
in Word.java
public class Word {
private String mConversation;
private int mImageResourceId = NO_IMAGE_PROVIDED;
public static final int NO_IMAGE_PROVIDED = -1;
public Word(String conversation){
mConversation = conversation;
}
public Word(String conversation, int imageResourceId){
mConversation = conversation;
mImageResourceId = imageResourceId;
}
public String getConversation(){
return mConversation;
}
public int getImageResourceId(){ return mImageResourceId; }
public boolean hasImage(){
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
in WordAdapter.java
public class WordAdapter extends ArrayAdapter {
private int mColorResourceId;
public WordAdapter(Context context, ArrayList<Word> worda){
super(context, 0, worda);
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null)
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
Word currentWord = (Word) getItem(position);
TextView convTextView = (TextView) listItemView.findViewById(R.id.conv_text_view);
convTextView.setText(currentWord.getConversation());
ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
if(currentWord.hasImage()) {
imageView.setImageResource(currentWord.getImageResourceId());
imageView.setVisibility(View.VISIBLE);
}
else {
imageView.setVisibility(View.GONE);
}
CheckBox checkbox = (CheckBox) listItemView.findViewById(R.id.checkBox2);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
View textContainer = listItemView.findViewById(R.id.text_container2);
textContainer.setBackgroundColor(((position % 2) == 0) ? Color.parseColor("#B2DFDB") : Color.parseColor("#80CBC4"));
return listItemView;
}
}
in list_item.xml
<?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="wrap_content"
android:background="#color/tan_background"
android:orientation="horizontal"
android:id="#+id/text_container2"
>
<ImageView
android:id="#+id/image"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:contentDescription="#null"
tools:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/conv_text_view"
style="#style/CategoryStyle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
tools:text="lutti" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
/>
</LinearLayout>
Use sharedpreferences to store the result.
boolean isChecked=false;
SharedPreferences pref = getSharedPreferences("prefs", MODE_PRIVATE);
Editor editor = pref.edit();
if(checkBox.isChecked()){
isChecked=true;
}
editor.putBoolean("checked", isChecked);
editor.apply()
retrieving the data from sharedPreferences.
write the below code just below setContentView();
if(prefs.getBoolean("checked","")==true){
checkBox.setChecked(true);
}

how to make a relevant toast only when press on a picture in a listview?

I made a list view with image and text view inside each view. what I'm trying to do is to make toast with the text from the text view every time I press on the image, and not when I press the rest of the view. I tried to use imageClick(View view) function that works when I press an image but I didn't find a way to get the text from the text view. another thing I tried was the onItemClick() function, so i can get the position of the view and get the text from the text view, but I can't check if the image was pressed or not.
anyway here's my code:
public class MainActivity extends AppCompatActivity {
int[] images = {R.drawable.pic_a, R.drawable.pic_b, R.drawable.pic_c,R.drawable.pic_d };
String[] names = {"aa","bb","cc","dd"};
String[] descriptions = {"1a","2a","3a","4a"};
List<ListViewItem> list = new ArrayList<>();
int lastPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateList();
ListView listView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(this,list);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
toast(names[position]);
}
});
}
public void imageClick(View view) {
}
private void populateList() {
int size = images.length;
for(int i = 0;i<size;i++){
ListViewItem item = new ListViewItem();
item.imageSource = images[i];
item.name = names[i];
item.description = descriptions[i];
list.add(item);
}
}
}
my listViewItem:
public class ListViewItem {
int imageSource;
String name;
String description;
}
and the XML:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
the second XML file:
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:id="#+id/imageView" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:id="#+id/textView_name" />
<TextView
android:text="TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignLeft="#+id/textView_name"
android:layout_alignStart="#+id/textView_name"
android:id="#+id/textView_description" />
and my CustomAdapter:
class CustomAdapter extends BaseAdapter {
private final Activity activity;
List<ListViewItem> list;
public CustomAdapter(Activity activity, List<ListViewItem> list){
super();
this.list = list;
this.activity = activity;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = this.activity.getLayoutInflater().inflate(R.layout.customlayout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
TextView textView_name = (TextView)view.findViewById(R.id.textView_name);
TextView textView_description = (TextView)view.findViewById(R.id.textView_description);
ListViewItem item = this.list.get(i);
imageView.setImageResource(item.imageSource);
textView_name.setText(item.name);
return view;
}
}

Simply expanding a recyclerview to show a TextView

I've explored many ways to achieve this. But I'm much confused now. I tried many Githubs libraries but got confused. Also tried this but I don't think it allows a textview to be shown in expanded view: http://bignerdranch.github.io/expandable-recycler-view/
WHAT I WANT: A simple Recyclerview fetching some text from server for different items. On each item click, a layout or view should be expanded and TextView should become visible with respective fetched text from the server.
I have a simple RecyclerView with code following:
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<List> android_versions;
private Context context;
int i =0;
public DataAdapter(Context context,ArrayList<List> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_android;
public ViewHolder(View view) {
super(view);
tv_android = (TextView)view.findViewById(R.id.tv_android);
}
}
List.java (Some functions aren't being used as of now)
public class List {
private String android_version_name;
private String descr;
private int android_image_url;
private String android_image_url1;
public String getAndroid_version_name() {
return android_version_name;
}
public String getDescr(){ return descr;}
public void setDescr(String descr) {
this.descr = descr;
}
public void setAndroid_version_name(String android_version_name) {
this.android_version_name = android_version_name;
}
public int getAndroid_image_url() {
return android_image_url;
}
public String getAndroid_image_url1() {
return android_image_url1;
}
public void setAndroid_image_url(int android_image_url) {
this.android_image_url = android_image_url;
}
public void setAndroid_image_url1(String android_image_url1) {
this.android_image_url1 = android_image_url1;
}
}
row_layout.xml
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp"
android:background="#drawable/custom_bg"
android:clickable="true"
android:translationZ="3dp"
android:elevation="1dp"
android:focusable="true">
<RelativeLayout
android:layout_marginLeft="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/custom_bg">
<TextView
android:layout_marginTop="10dp"
android:textSize="20sp"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_android"
android:textStyle="normal"
android:layout_centerVertical="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Work.java (It's a fragment)
String[] sublist={
"English",
"Hindi"
};
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
rcl = (RecyclerView) getActivity().findViewById(R.id.homeworklist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rcl.setLayoutManager(layoutManager);
dataAdapter = new DataAdapter(getActivity(), new ArrayList<>(prepareData()));
rcl.setAdapter(dataAdapter);
}
public ArrayList prepareData(){
ArrayList android_version = new ArrayList<>();
for(int i=0;i<sublist.length;i++){
List androidVersion = new List();
androidVersion.setAndroid_version_name(sublist[i]);
android_version.add(androidVersion);
break;
}
return android_version;
}

Android: calling getview() for ListView's Adapter from Fragment in viewPager

I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>

How to send the right context to the new object

I have public class PageFragment that extends Fragment to create 6 pages with views that fills by another class.
Here are the PageFragment class:
public class PageFragment extends Fragment {
static final String arg_page_number = "arg_page_number";
int pageNumber;
int backColor;
public LinearLayout framesContainer;
ExecutorService ex = Executors.newCachedThreadPool();
Future<ArrayList<ElementData>> s = ex.submit(new MyThread());
public static PageFragment newInstance(int page) {
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(arg_page_number, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(arg_page_number);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_row, null);
framesContainer = (LinearLayout) view.findViewById(R.id.frames_container);
for (int i = 0; i < 20; i += 4) {
Frame frame = new Frame(getApplicationContext());
try {
frame.setStudyName(s.get().get(0).Days().get(i));
frame.setStudyKindName(s.get().get(0).Days().get(i + 1));
frame.setAuditorium(s.get().get(0).Days().get(i + 2));
frame.setLectureTitle(s.get().get(0).Days().get(i + 3));
framesContainer.addView(frame);
} catch (Exception e) {
e.printStackTrace();
}
}
return view;
}
class MyThread implements Callable<ArrayList<ElementData>> {
public ArrayList<ElementData> call() {
ArrayList<ElementData> elementDataArrayList = Parser.parse("url");
return elementDataArrayList;
}
}}
And this is MyActivity:
public class MyActivity extends FragmentActivity {
/**
* Called when the activity is first created.
*/
static final String TAG = "myLogs";
static final int PAGE_COUNT = 6;
ViewPager pager;
PagerAdapter pagerAdapter;
SharedPreferences sPref;
String[] groups = {....};
final String SAVED_TEXT = "SavePref";
private LinearLayout framesContainer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sPref = getPreferences(MODE_PRIVATE);
if (sPref.getBoolean(SAVED_TEXT, true)) {
setContentView(R.layout.startpage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, groups);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(adapter);
final int selectionCurrent = spinner.getSelectedItemPosition();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (selectionCurrent != position) {
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putBoolean(SAVED_TEXT, false);
ed.commit();
setContentView(R.layout.main);
pager = (ViewPager) findViewById(R.id.frames_container);
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected, position = " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
} else {
setContentView(R.layout.main);
pager = (ViewPager) findViewById(R.id.frames_container);
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected, position = " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}}
When i'm using getApplicationContext is shows me error of unresolved method.
Do i need to cast MyActivity's context here? How can i do that?
Frame class:
public class Frame extends RelativeLayout {
private TextView StudyName;
private TextView Auditorium;
private TextView StudyKindName;
private TextView LectureTitle;
public Frame(Context context) {
super(context);
initComponent();
}
private void initComponent() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.table_row, this);
StudyName = (TextView) findViewById(R.id.StudyName);
Auditorium = (TextView) findViewById(R.id.Auditorium);
StudyKindName = (TextView) findViewById(R.id.StudyKindName);
LectureTitle = (TextView) findViewById(R.id.LectureTitle);
}
public void setStudyName(String study_Name) {
StudyName.setText(study_Name);
}
public void setAuditorium(String auditorium) {
Auditorium.setText(auditorium);
}
public void setStudyKindName(String studyKindName) {
StudyKindName.setText(studyKindName);
}
public void setLectureTitle(String lectureTitle) {
LectureTitle.setText(lectureTitle);
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/frames_container"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
table_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/program_frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<TextView
android:id="#+id/StudyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#android:color/white"
android:textStyle="normal"
android:textSize="16sp"
android:text="StudyName"/>
<TextView
android:id="#+id/Auditorium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:textColor="#android:color/darker_gray"
android:textStyle="bold"
android:textSize="16sp"
android:singleLine="true"
android:text="Auditorium"/>
<TextView
android:id="#+id/StudyKindName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/StudyName"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:textColor="#android:color/darker_gray"
android:textStyle="bold"
android:textSize="15sp"
android:singleLine="true"
android:text="StudyKindName"/>
<TextView
android:id="#+id/LectureTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/StudyKindName"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dip"
android:textColor="#android:color/darker_gray"
android:textStyle="normal"
android:textSize="12sp"
android:text="Lector"/>
<ImageView
android:id="#+id/imageView2"
android:layout_below="#id/LectureTitle"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="15dip"
android:background="#bb333333" />
</RelativeLayout>
You can use getActivity().getApplicationContext() in Fragment.
I don't know what Frame is in Frame frame = new Frame(getApplicationContext());. In case you are doing ui stuff use only getActivity().
Read
When to call activity context OR application context?

Categories

Resources