my RecyclerView does not show anything - java

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.

Related

Add and show items to the RecyclerView in different fragments

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;
}
}

Listview in dynamically created ListFragment doesn't appear

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?

Android Recyclerview not showing any data

I took this tutorial as reference.
Despite of checking everything, no data is appearing on screen ie. main_activity. I've already referred to other pages on stackoverflow regarding this issue. Can't find a viable solution.
NOTE: There is no warning or error while I deploy app on the device.
This is the source code.
MainActivity.java:
public class MainActivity extends Activity
{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
DataObject obj = new DataObject("red", "foo");
((MyRecyclerViewAdapter) mAdapter).addItem(obj, 0);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < 20; index++){
DataObject obj = new DataObject("Some Primary Text " + index, "Secondary " + index);
results.add(index, obj);
}
return results;
}
}
DataObject.java:
public class DataObject {
private String mText1;
private String mText2;
DataObject (String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
MyRecyclerViewAdapter.java:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder>
{
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView label;
TextView dateTime;
public DataObjectHolder(View itemView)
{
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount()
{
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
DividerIconDecoration.java
public class DividerItemDecoration extends RecyclerView.ItemDecoration{
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
#Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
#Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
activity_main.xml
<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="${relativePackage}.${activityClass}" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</RelativeLayout>
</ScrollView>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
The problem is in activity_main.xml. You should remove ScrollView and it will work (There's no reason to have one since the recyclerview has an implicit one). There is no scrollview in the tutorial either: check activity_recycler_view.xml.

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>

Custom ArrayAdapter showing a blank screen in my Fragment

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();
}

Categories

Resources