I'm currently developing an App where I want to use a bottom Navigation with multiple dynamically created Fragments.
Therefore I set up a test app to get used to these funtions.
The problem is now, if I create the ListFragment by a static XML the ListView is created correctly, but If I create it dynamically the ListView does not get displayed, only the BottomNavigation is displayed, nothing else.
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment();
}
private void addFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyListFragment myListFragment = new MyListFragment();
fragmentTransaction.add(R.id.fragmentContainer, myListFragment);
fragmentTransaction.commit();
}
}
Layout:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentContainer"
android:layout_margin="5dp"
android:layout_alignTop="#+id/bottom_nav"/>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="48dp"
android:id="#+id/bottom_nav"
app:menu="#menu/menu_bottom_nav"
android:background="#808080"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
ListFragment:
public class MyListFragment extends ListFragment implements AdapterView.OnItemClickListener {
CustomerAdapter customerAdapter;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Customer customer = new Customer("Testcustomer","123456", "654321");
customerAdapter = new CustomerAdapter(Objects.requireNonNull(getActivity()),R.layout.list_pack_item);
listView = new ListView(getActivity());
listView.setAdapter(customerAdapter);
customerAdapter.add(customer);
listView.setOnItemClickListener(this);
return listView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//do stuff
}
}
CustomerAdapter:
public class CustomerAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomerAdapter(#NonNull Context context, int resource ) {
super(context, resource);
}
public void add( #Nullable Customer object ) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position ) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent ) {
View row;
row = convertView;
CustomerHolder customerHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.list_pack_item, parent, false);
customerHolder = new CustomerHolder();
customerHolder.tx_name = row.findViewById(R.id.tx_name);
customerHolder.tx_intern = row.findViewById(R.id.tx_intern);
customerHolder.tx_extern = row.findViewById(R.id.tx_extern);
row.setTag(customerHolder);
} else {
customerHolder = (CustomerHolder) row.getTag();
}
Customer customer = (Customer) this.getItem(position);
customerHolder.tx_name.setText(customer.getName());
customerHolder.tx_intern.setText("Internal Number: " + customer.getMyCustomerNumber());
customerHolder.tx_extern.setText("Supplier Number: " + customer.getSupplierNumber());
return row;
}
static class CustomerHolder {
TextView tx_name, tx_intern, tx_extern;
}
}
Customer Class
public class Customer {
private String name;
private String supplierNumber;
private String myCustomerNumber;
public Customer(String name, String supplierNumber, String myCustomerNumber) {
this.name = name;
this.supplierNumber = supplierNumber;
this.myCustomerNumber = myCustomerNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplierNumber() {
return supplierNumber;
}
public void setSupplierNumber(String supplierNumber) {
this.supplierNumber = supplierNumber;
}
public String getMyCustomerNumber() {
return myCustomerNumber;
}
public void setMyCustomerNumber(String myCustomerNumber) {
this.myCustomerNumber = myCustomerNumber;
}
}
If there is any further information or code needed please let me know!
Additionally: I need to create the fragments dynamically in order to replace them, am I correct?
Related
I am creating an app that has 3 Tabs and every tabs has a different jobs. For Example, In Employee tab, there are EditText for taking name and surname of an emolyee and Button for add items to the its RecyclerView. City Tab is same as Employee tab just takes city names. The last tab has only one Button for distribute entries of Employees and Cities and show to user.
My problem is, I cannot find how to add items to the RecyclerView and and show it to the user.
Here is my code. I am sending just Tab1's fragment and layouts. Others are the same.
This is the Fragment1 class:
public class Fragment1 extends Fragment {
private RecyclerView employeeRecyclerView;
private RecyclerViewAdapter employeeRecyclerViewAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.name_employee, container, false);
}
}
This is the RecyclerViewAdapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private List<String> mData;
private LayoutInflater mInflater;
RecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_main, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
String x = mData.get(position);
holder.myTextView.setText(x);
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.section_label);
}
}
}
and Employee.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/employeeField"
android:hint="Name and Surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<Button
android:id="#+id/cityAdd"
android:text="addEmployee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/employees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
and fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Update I upload other classes. There are Fragment2 and Fragment3 classes but they are same with Fragment1.
PlaceHolderFragment.class
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
final TextView textView = root.findViewById(R.id.section_label);
pageViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
SectionsPagerAdapter.class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
return 3;
}
}
and PageViewModel.class
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
#Override
public String apply(Integer input) {
return "Hello world from section: " + input;
}
});
public void setIndex(int index) {
mIndex.setValue(index);
}
public LiveData<String> getText() {
return mText;
}
}
I want to display Fragments in a ViewPager however it is only showing the first Fragment in the view tabs. The only fragment that gets shown is the one returned at postion 0 in the getItem(0 method - this fragment is displayed in subsequent views.
FragmentPagerAdapter:
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
public SimpleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new WorldFragment();
} else if (position == 1) {
return new PoliticsFragment();
} else if (position == 2) {
return new TechnologyFragment();
} else if (position == 3) {
return new ScienceFragment();
} else if (position == 4) {
return new SportsFragment();
} else if (position == 5) {
return new FoodFragment();
} else if (position == 6) {
return new TravelFragment();
} else if (position == 7) {
return new MoviesFragment();
} else if (position == 8) {
return new FashionFragment();
} else {
return new OpinionFragment();
}
}
#Override
public int getCount() {
return 10;
}
}
Fragment:
public class WorldFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Story>> {
public static final String LOG_TAG = WorldFragment.class.getName();
private static final String NY_TIMES_REQUEST_URL = "https://api.nytimes.com/svc/topstories/v2/world.json?api-key=<API KEY REMOVED>;
private StoryAdapter mAdapter;
private TextView mEmptyTextView;
private View rootView;
public WorldFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.story_list, container, false);
mAdapter = new StoryAdapter(getActivity(), new ArrayList<Story>());
final ListView listView = (ListView) rootView.findViewById(R.id.story_list);
mEmptyTextView = (TextView) rootView.findViewById(R.id.empty_textview);
listView.setEmptyView(mEmptyTextView);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Story currentStory = mAdapter.getItem(position);
String url = currentStory.getmURL();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
LoaderManager loaderManager = getActivity().getLoaderManager();
loaderManager.initLoader(0, null, this);
} else {
View loadingIndicator = rootView.findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyTextView = (TextView) rootView.findViewById(R.id.empty_textview);
mEmptyTextView.setText(R.string.no_internet_connection);
}
return rootView;
}
#Override
public android.content.Loader<List<Story>> onCreateLoader(int i, Bundle bundle) {
return new StoryLoader(getActivity(), NY_TIMES_REQUEST_URL);
}
#Override
public void onLoadFinished(android.content.Loader<List<Story>> loader, List<Story> stories) {
mAdapter.clear();
View loadingIndicator = rootView.findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyTextView.setText(R.string.no_new_stories);
if (stories != null && !stories.isEmpty()) {
mAdapter.addAll(stories);
}
}
#Override
public void onLoaderReset(android.content.Loader<List<Story>> loader) {
mAdapter.clear();
}
#Override
public void onStop() {
super.onStop();
}
}
ViewPager XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.topworldstories.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
List XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent">
<ListView
android:id="#+id/story_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true" />
<TextView
android:id="#+id/empty_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
tools:text="No new stories"/>
<ProgressBar
android:id="#+id/loading_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_centerInParent="true"/>
</LinearLayout>
I am unsure of what is causing this. Any help is appreciated
it is only showing the first Fragment multiple times in the view tabs
Two possibilities I see, both of which are copy-paste errors.
1) You didn't change this URL (notice world.json)
private static final String NY_TIMES_REQUEST_URL = "https://api.nytimes.com/svc/topstories/v2/world.json?api-key=<API KEY REMOVED>";
2) You didn't use a different layout.
rootView = inflater.inflate(R.layout.story_list, container, false);
But since your data seems to be consistent, I'm guessing #1 is true.
If you have 10 different URL's that you want to display in the same "fragment layout", you do not need 10 separate Fragment files.
For example, one Fragment
public class NyTimesFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Story>> {
public static final String LOG_TAG = NyTimesFragment.class.getName();
private static final String NY_TIMES_URL = "nyTimesURL";
private StoryAdapter mAdapter;
private TextView mEmptyTextView;
private View rootView;
public NyTimesFragment(String url) {
Bundle b = new Bundle();
b.putExtra(NY_TIMES_URL, url); // Pass URL here
setArguments(b);
}
public NyTimesFragment() {
// Required empty public constructor
}
#Override
public android.content.Loader<List<Story>> onCreateLoader(int i, Bundle bundle) {
// Load url here
String url = getArguments().getString(NY_TIMES_URL);
return new StoryLoader(getActivity(), url);
}
That you pass any NyTimes URL to
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
// List of NyTimes topics
private String[] topics = { "world", "politics" };
// !!! Do NOT store this in your app... !!!
private static final String API_KEY = "XXXXX";
public SimpleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
private String getURL(String apiKey, String topic) {
return String.format(
"https://api.nytimes.com/svc/topstories/v2/%s.json?api-key=%s",
topic, apiKey);
}
#Override
public int getCount() {
return topics.length; // Assuming each fragment goes to NyTimes
}
#Override
public Fragment getItem(int position) {
final String url = getURL(topics[position], API_KEY);
// Call the other constructor
return new NyTimesFragment(url);
} // done... no if statements.
Something to consider to make this somewhat better would be Retrofit + Gson...
Ok so the issue here is I was using the same loader id in initloader for each fragment & this is why the same data was being loaded. The loader id needs to be unique for each fragment for this to work.
Help. I don't know why my RecyclerView does not show anything. My implementation of the adapter is right. I don't know where have I gone wrong.
Here's the Fragment class:
public class RemittanceFragment extends Fragment implements View.OnClickListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
#BindView(R.id.remit_cancel_view)
View remitCancelView;
#BindView(R.id.remit_checkpaid_view)
View remitCheckPaidView;
#BindView(R.id.remit_create_view)
View remitCreateView;
#BindView(R.id.remit_main_menu)
View remitMainMenuView;
#BindView(R.id.btn_cancel)
Button btnCancel;
#BindView(R.id.btn_checkpaid)
Button btnCheckPaid;
#BindView(R.id.btn_create)
Button btnCreate;
#BindView(R.id.btn_back)
TextView btnGoBack;
#BindView(R.id.btn_back2)
TextView btnGoBack2;
#BindView(R.id.remit_header_title)
TextView tvRemitHeaderTitle;
#BindView(R.id.remit_cancel_list)
RecyclerView cancelRecyclerView;
public RemittanceFragment() {
// Required empty public constructor
}
public static RemittanceFragment newInstance() {
RemittanceFragment fragment = new RemittanceFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_remit_menu, container, false);
ButterKnife.bind(this, view);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
btnCancel.setOnClickListener(this);
btnCreate.setOnClickListener(this);
btnCheckPaid.setOnClickListener(this);
btnGoBack.setOnClickListener(this);
btnGoBack2.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
remitMainMenuView.setVisibility(View.GONE);
switch (v.getId()) {
case R.id.btn_cancel:
remitCancelView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CANCEL\nREMITTANCE");
populateData();
break;
case R.id.btn_checkpaid:
remitCheckPaidView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CHECK / PAID\nREMITTANCE");
break;
case R.id.btn_create:
remitCreateView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CREATE\nREMITTANCE");
break;
case R.id.btn_back:
case R.id.btn_back2:
remitMainMenuView.setVisibility(View.VISIBLE);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
tvRemitHeaderTitle.setText("REMITTANCE");
break;
default:
break;
}
}
public void populateData() {
List<RemitTransaction> transactions = new ArrayList<>();
transactions = RemitTransaction.createRemitTransactionList();
RemitTransactionListAdapter adapter = new RemitTransactionListAdapter
(transactions, getActivity());
cancelRecyclerView.setAdapter(adapter);
cancelRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
public static class RemitTransaction {
private String mRefno;
private String mDate;
private String mMsisdn;
private String mAmount;
public RemitTransaction(String refno, String date, String msisdn, String amount) {
mRefno = refno;
mDate = date;
mMsisdn = msisdn;
mAmount = amount;
}
public String getmRefno() {
return mRefno;
}
public String getmDate() {
return mDate;
}
public String getmMsisdn() {
return mMsisdn;
}
public String getmAmount() {
return mAmount;
}
public static ArrayList<RemitTransaction> createRemitTransactionList() {
ArrayList<RemitTransaction> transactions = new ArrayList<>();
for (int n = 0; n < 4; n++) {
transactions.add(n, new RemitTransaction(
"REF01253123" + n,
"July " + n + ", 2016",
"0920987654" + n,
"100" + n));
}
return transactions;
}
}
public class RemitTransactionListAdapter
extends RecyclerView.Adapter<RemitTransactionListAdapter.CancelVH>{
private List<RemitTransaction> mList;
private Context mContext;
public RemitTransactionListAdapter(List<RemitTransaction> list, Context context) {
mList = list;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CancelVH onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = getContext();
View v = LayoutInflater.from(context).inflate(R.layout.remit_cancel_list_item, parent, false);
return new CancelVH(v);
}
#Override
public void onBindViewHolder(CancelVH holder, int position) {
RemitTransaction transaction = mList.get(position);
holder.cancelRefno.setText(transaction.getmRefno());
holder.cancelAmount.setText(transaction.getmAmount());
holder.cancelDate.setText(transaction.getmDate());
holder.cancelMsisdn.setText(transaction.getmMsisdn());
}
#Override
public int getItemCount() {
return mList.size();
}
public class CancelVH extends RecyclerView.ViewHolder {
#BindView(R.id.remit_item_refno) TextView cancelRefno;
#BindView(R.id.remit_item_amount) TextView cancelAmount;
#BindView(R.id.remit_item_date) TextView cancelDate;
#BindView(R.id.remit_item_msisdn) TextView cancelMsisdn;
public CancelVH(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
}
And here's the layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/utility_white"
android:paddingTop="#dimen/dimen_margin_vertical_extra_large">
<android.support.v7.widget.RecyclerView
android:id="#+id/remit_cancel_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And here's the list_item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/remit_item_refno"
style="#style/RemitListItem"
android:text="VW832191"
android:textStyle="bold"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/remit_item_amount"
style="#style/RemitListItem"
android:text="100.00"
android:textStyle="bold"
android:layout_alignParentEnd="true"/>
<TextView
android:id="#+id/remit_item_date"
style="#style/RemitListItem"
android:text="2016-07-20"
android:layout_alignParentStart="true"
android:layout_below="#+id/remit_item_refno"/>
<TextView
android:id="#+id/remit_item_msisdn"
style="#style/RemitListItem"
android:text="09273450686"
android:layout_alignParentEnd="true"
android:layout_below="#+id/remit_item_amount"/>
</RelativeLayout>
Hope you can all help me. Thank you!
in previous versions of support library 23.2.0 wrap_content not work for RecyclerView ,and with support library 23.2.0 and above wrap_content work perfectly (now latest version is 24.0.0),
i guess that is your problem.
i'm having some issues implementing a Sliding Tabs activity that contains 2 Fragments and a Swipe Down to Refresh layout, namely implementing the Swipe Down to Refresh part (the rest is working just fine).
First here are my XML files.
The Main Activity XML , which contains the ViewPager wrapped in an SwipeRefreshLayout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.popal.soul.MovieListActivityTEST">
<com.example.popal.soul.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.SwipeRefreshLayout>
And the first tab XML , one of the 2 tabs (both are similar, so i`ll only post one)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Now, my main activity, which handles the ViewPager, Adapter an the SlidingTabsLayout.
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
And finally, my fragment for the first Tab
public class Tab1 extends Fragment {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
private SwipeRefreshLayout swipeContainer;
private List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
private ProgressBar progressBar;
private final static String MOVIES_POST_REQUEST ="//Long String, Edited out since it`s not relevant"
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
movieListAdaptor.clear();
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
swipeContainer.setRefreshing(false);
}
});
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
The issue is, i'm getting a NULL Pointer Exception at swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...} method, which i guess is because the Swipe-to-Refresh layout is in the main activity XML, and not the tabs fragment. So what is the proper way to implement this ? I also tried implementing a Swipe to refresh layout in one of the Tabs XML instead of wrapping the ViewPager in it, like above, but it would crash when swiping from tab to another.
Here`s the code from the entire fragment in Tab1, for tobs answer below
public class MoviesTabFragment extends Fragment implements Refreshable {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
//private SwipeRefreshLayout swipeContainer;
public List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
public ProgressBar progressBar;
public final static String MOVIES_POST_REQUEST ="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
#Override
public void refresh() {
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
}
public class Send_data_to_server extends AsyncTask<String, Void, String> {
private String data_poster;
private String data_fanart;
// protected void onPreExecute() {
// progressBar.setVisibility(View.VISIBLE);
// }
protected String doInBackground(String... params)
{
String jason_data = params[0];
HttpClient http_con = new HttpClient();
String output_from_server = http_con.establish_con(jason_data);
Log.i("DataFromServer", output_from_server);
JSONObject json_Obj = null;
JSONObject child_obj = null; //creating the "result" object in the main JSON Object
try {
json_Obj = new JSONObject(output_from_server);
child_obj = create_subObject("result", json_Obj);
JSONArray jsonArray = child_obj.optJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title_data = jsonObject.optString("label").toString();
String plot_data = jsonObject.optString("plot").toString();
String year_data = jsonObject.optString("year").toString();
String movie_id_data = jsonObject.optString("movieid").toString();
String imdb_score = jsonObject.optString("rating").toString();
String imdb_score_short = imdb_score.substring(0, 3);
JSONObject child_obj2 = create_subObject("art", jsonObject);
data_poster = child_obj2.optString("poster").toString();
data_fanart = child_obj2.optString("fanart").toString();
JSONEncodePosterFanart encodePosterFanart = new JSONEncodePosterFanart();
String jason_dataPoster = encodePosterFanart.GetPosterFanartEncodedURL(data_poster);
String jason_dataFanart = encodePosterFanart.GetPosterFanartEncodedURL(data_fanart);
HttpClient http = new HttpClient();
String output_from_serverPoster = http.establish_con(jason_dataPoster);
HttpClient http2 = new HttpClient();
String output_from_serverFanart = http2.establish_con(jason_dataFanart);
JSONPosterFanart poster_fanart = new JSONPosterFanart();
String post_dl = poster_fanart.GetPosterFanart(output_from_serverPoster);
JSONPosterFanart poster_fanart2 = new JSONPosterFanart();
String fanart_dl = poster_fanart2.GetPosterFanart(output_from_serverFanart);
if (null == movieList) {
movieList = new ArrayList<MovieListAdapter.MovieDetails>();
}
MovieListAdapter.MovieDetails item = new MovieListAdapter.MovieDetails(title_data+" ("+year_data+")", post_dl, fanart_dl,plot_data,movie_id_data,imdb_score_short);
movieList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return output_from_server;
}
protected void onPostExecute(String output_from_server) {
super.onPostExecute(output_from_server);
//progressBar.setVisibility(View.INVISIBLE);
movieListAdaptor = new MovieListAdapter(getActivity(), movieList);
recycleList.setAdapter(movieListAdaptor);
}
private JSONObject create_subObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName); //getJSONObject returns the value from tagName (in our case jason_Obj that is being passed ar a param)
return subObj;
}
}
}
And the RecycleView adapter:
public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder> {
public List<MovieDetails> movieList;
private Context mContext;
public MovieListAdapter(Context mContext, List<MovieDetails> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public int getItemCount() {
return movieList.size();
}
public void clear() {
movieList.clear();
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout_movies_list, viewGroup, false);
return new MovieViewHolder(itemView);
}
#Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {
MovieDetails mdet = movieList.get(i);
String fanart = "http://192.168.1.128/"+mdet.getImageViewFanart();
String poster = "http://192.168.1.128/"+mdet.getImageViewPoster();
Log.i("fanart", fanart);
Log.i("poster", poster);
movieViewHolder.vTitle.setText(mdet.Title);
Picasso.with(mContext).load(poster)
.resize(500, 746)
.error(R.drawable.poster_placeholder)
.placeholder(R.drawable.poster_placeholder)
.into(movieViewHolder.vPoster);
Picasso.with(mContext).load(fanart)
.resize(960, 540)
.error(R.drawable.fanart_placeholder)
.placeholder(R.drawable.fanart_placeholder)
.into(movieViewHolder.vFanart);
movieViewHolder.vplot = mdet.getPlot();
movieViewHolder.vmovie_id = mdet.getMovie_id();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView vTitle;
protected ImageView vPoster;
protected ImageView vFanart;
protected String vplot;
protected String vmovie_id;
protected String vimdb_score;
public MovieViewHolder(View v)
{
super(v);
vplot = new String();
vmovie_id = new String();
vimdb_score = new String();
vTitle = (TextView) v.findViewById(R.id.title);
vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
MovieDetails mov = movieList.get(position);
Intent intent = new Intent(mContext, MovieDetailsPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("movieid", mov.getMovie_id());
bundle.putString("plot", vplot);
bundle.putString("fanart_path", mov.getImageViewFanart());
bundle.putString("imdb_score", mov.getImdb_score());
intent.putExtras(bundle);
mContext.startActivity(intent);
}
}
public static class MovieDetails {
protected String Title;
protected String imageViewPoster;
protected String imageViewFanart;
protected String plot;
protected String movie_id;
protected String imdb_score;
public MovieDetails(String Title, String imageViewPoster,String imageViewFanart, String plot, String movie_id ,String imdb_score)
{
this.Title = Title;
this.imageViewPoster = imageViewPoster;
this.imageViewFanart = imageViewFanart;
this.plot = plot;
this.movie_id = movie_id;
this.imdb_score = imdb_score;
}
public String getTitle() {return Title;}
public String getImageViewPoster() {
return imageViewPoster;
}
public String getImageViewFanart() {
return imageViewFanart;
}
public String getPlot() {return plot;}
public String getMovie_id() {return movie_id;}
public String getImdb_score() {return imdb_score;}
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
MoviesTabFragment moviesTabFragment = new MoviesTabFragment();
return moviesTabFragment;
}
else
{
TVShowsTabFragment TVShowsTabFragment = new TVShowsTabFragment();
return TVShowsTabFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
You're getting the NullPointerException because you inflate your fragment layout from R.layout.tab_1 which does not contain a SwipeRefreshLayout.
If you want the layout to be the parent of your ViewPager, I would recommend you to move your code which manages the RefreshLayout to the MainActivity:
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SwipeRefreshLayout refreshLayout;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
// Assign your refresh layout
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Refreshable r = (Refreshable) adapter.getItemAt(pager.getCurrentItem());
r.refresh();
}
});
}
where each of your tab fragments implements a Refreshable interface:
public interface Refreshable {
void refresh();
}
and your adapter keeps track on all fragments:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// list that keeps references to all attached Fragments
private SparseArray<Fragment> pages = new SparseArray<>();
...
public Fragment getItem(int position) {
Fragment f;
if(position == 0) {
...
} else { ... }
// add fragment to the list
pages.put(position, f);
}
public void destroyItem(ViewGroup container, int position, Object object) {
// remove fragment from list if it existed
if(pages.indexOfKey(position) >= 0) {
pages.remove(position);
}
super.destroyItem(container, position, object);
}
// return the attached Fragment that is associated with the given position
public Fragment getItemAt(int position) {
return pages.get(position);
}
}
So I've just been messing around with android for a little bit and I've run into a bit of a snag. The fragment where I am instantiating ListOfJokesTypesAdapter for some reason is not displaying a listview populated with the Data from my JokeData class.
All that I get is a blank screen (no errors or anything of that nature).
This is just a proof of concept thing I've been working on so any help would be greatly appreciated. Why is it that this particular custom adapter is not working while my MainClassAdapter is working just fine.
The Code
My Joke Class:
public class Joke {
private String jokeSetup;
private String jokePunchline;
public Joke(String jokeSetup, String jokePunchline) {
this.jokeSetup = jokeSetup;
this.jokePunchline = jokePunchline;
}
public String getJokeSetup() {
return jokeSetup;
}
public void setJokeSetup(String jokeSetup) {
this.jokeSetup = jokeSetup;
}
public String getJokePunchline() {
return jokePunchline;
}
public void setJokePunchline(String jokePunchline) {
this.jokePunchline = jokePunchline;
}
}
My JokeListClass
public class JokeListData {
private String listName;
private List<Joke> arrayListOfJokes;
public JokeListData(String listName, List<Joke> arrayListOfJokes) {
this.listName = listName;
this.arrayListOfJokes = arrayListOfJokes;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public List<Joke> getArrayListOfJokes() {
return arrayListOfJokes;
}
public void setArrayListOfJokes(ArrayList<Joke> arrayListOfJokes) {
this.arrayListOfJokes = arrayListOfJokes;
}
}
My Actual Joke Data
public class JokeData {
private static List<Joke> dogJokes = new ArrayList<Joke>(){
{
add(new Joke("Dogs", "Bark"));
add(new Joke("Dogs", "Woof"));
add(new Joke("Dogs", "Howl"));
add(new Joke("Dogs", "Sniff"));
}
};
private static List<Joke> catJokes = new ArrayList<Joke> (){
{
add(new Joke("Cats", "woof"));
add(new Joke("Dogs", "Meow"));
}
};
static List<JokeListData> dataOfJokeList = new ArrayList<JokeListData>();
public static void addEntries(){
dataOfJokeList.add(new JokeListData("Cat Jokes", catJokes));
dataOfJokeList.add(new JokeListData("Dog Jokes", dogJokes));
}
}
The Adapter
public class ListOfJokeTypesAdapter extends ArrayAdapter<JokeListData> {
Context mContext;
int mLayoutId;
List<JokeListData> mList;
public ListOfJokeTypesAdapter(Context context, int resource, List<JokeListData> objects) {
super(context, resource, objects);
this.mContext = context;
this.mLayoutId = resource;
this.mList = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mLayoutId,parent,false);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.rowForMainList);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
return convertView;
}
private static class ViewHolder{
TextView mTextView;
}
}
The Fragment which utilizes the adapter
public class ListOfJokeTypesFragment extends Fragment {
ListView mListView;
ListOfJokeTypesAdapter listOfJokeTypesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_type_fragment,container,false);
JokeData.addEntries();
mListView = (ListView)view.findViewById(R.id.jokeTypeListView);
listOfJokeTypesAdapter = new ListOfJokeTypesAdapter(getActivity().getApplicationContext(),R.layout.row,JokeData.dataOfJokeList);
mListView.setAdapter(listOfJokeTypesAdapter);
return view;
}
}
The Fragment Manager
package com.example.taranveer.jokeapplicationactual;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Taranveer on 2014-07-22.
*/
public class TheFragmentActivityManager extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
Bundle args = getIntent().getExtras();
if(findViewById(R.id.container) != null){
if(args != null){
if(args.getInt("randomjoke") == 1){
RandomJokeFragment randomJokeFragment = new RandomJokeFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container, randomJokeFragment)
.commit();
}
}
}
if(findViewById(R.id.container) != null){
if(args!=null){
if(args.getInt("listofjoketypes") == 2){
ListOfJokeTypesFragment listOfJokeTypesFragment = new ListOfJokeTypesFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container,listOfJokeTypesFragment)
.commit();
}
}
}
}
}
The relevant XML:
joke_type_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/jokeTypeListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="5dp"
android:gravity="center_vertical"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#eeeeee"
android:textStyle="bold"
android:layout_margin="5dp"
android:padding="5dp"
android:background="#2299dd"
android:textSize="20sp"
android:text="Main Activity Items"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rowForMainList"/>
</LinearLayout>
</LinearLayout>
better to put these lines
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
inside if(convertView == null) condition
beforr#Override
public int getCount() {
return super.getCount();
}
remove this line
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
Replace
#Override
public int getCount() {
return super.getCount();
}
With something like
#Override
public int getCount() {
return mySourceArrayList.getCount();
}