RecyclerView only display the first item - java

I'm trying to get data from a SQLite Database , and display it on a RecyclerView . However , the adapter only displays the first item . Many related topics are talking about changing the height of the parent layout to xxdp or to wrap_content , which I tried . Here is the code :
QuoteAdapter.java:
public class QuoteAdapter extends RecyclerView.Adapter<QuoteAdapter.QuoteViewHolder> {
private QuoteItemBinding binding;
private Context mContext;
private Cursor mCursor;
public QuoteAdapter(Context context,Cursor cursor) {
this.mContext = context;
this.mCursor = cursor;
}
#Override
public QuoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
binding = DataBindingUtil.setContentView(
(Activity)mContext, R.layout.quote_item);
int quoteLayoutId = R.layout.quote_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(quoteLayoutId,parent,shouldAttachToParentImmediately);
QuoteViewHolder quoteViewHolder = new QuoteViewHolder(view);
return quoteViewHolder;
}
#Override
public void onBindViewHolder(QuoteViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)) {
return;
}
String category = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_CATEGORY));
String author = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_AUTHOR));
String quote = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_CONTENT));
Log.d(this.getClass().getSimpleName(),quote);
holder.mQuoteAuthor.setText(author);
holder.mQuoteCategory.setText(category);
holder.mQuoteTextView.setText(quote);
//Passer l'ID en tag du itemView avec holder.itemView.setTag(id) si on veut une action paritculiere sur un item
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public void swapCursor(Cursor newCursor) {
if(mCursor != null) mCursor.close();
mCursor = newCursor;
if(newCursor != null) {
this.notifyDataSetChanged();
}
}
public class QuoteViewHolder extends RecyclerView.ViewHolder{
public TextView mQuoteTextView;
public TextView mQuoteAuthor;
public TextView mQuoteCategory;
public QuoteViewHolder(View itemView) {
super(itemView);
mQuoteTextView = binding.quote;
mQuoteAuthor = binding.quoteAuthor;
mQuoteCategory = binding.quoteCategory;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Selected",Toast.LENGTH_LONG).show();
}
});
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private QuoteAdapter mQuoteAdapter;
private SQLiteDatabase mDb;
private static final String TAG = MainActivity.class.getSimpleName();
private ActivityMainBinding mainBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
RecyclerView quoteListRecycler = mainBinding.recyclerMain;
quoteListRecycler.setLayoutManager(new LinearLayoutManager(this));
QuoteDbHelper dbHelper = new QuoteDbHelper(this);
mDb = dbHelper.getWritableDatabase();
Cursor cursor = getAllQuotes();
mQuoteAdapter = new QuoteAdapter(this,cursor);
quoteListRecycler.setAdapter(mQuoteAdapter);
}
private Cursor getAllQuotes() {
return mDb.query(QuoteContract.QuoteEntry.TABLE_NAME,
null,
null,
null,
null,
null,
QuoteContract.QuoteEntry.COLUMN_DATE);
}
}
quote_item.xml
<?xml version="1.0" encoding="utf-8"?>
android:paddingBottom="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:id="#+id/item_for_recycler"
android:layout_width="match_parent"
android:layout_height="56dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quoteCategory"
style="#style/TextAppearance.AppCompat.Display2"
android:paddingLeft="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:textSize="10sp"
tools:text="Category : Business"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quote"
tools:text="Hello there"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quoteAuthor"
android:layout_gravity="bottom|right"
style="#style/TextAppearance.AppCompat.Display2"
android:paddingLeft="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:paddingRight="#dimen/quote_item_padding"
android:textSize="10sp"
tools:text="Leonardo DeMontesquieu"
/>
</FrameLayout>
</layout>
Thank you in advance !

Related

fragment recyclerview different view types not working

Android fragment recyclerview different view types not working
I have implement different view types using recyclerview adapter but list are empty this time not display empty view type.
First implement fragment
Second add recyclerview in fragment.
Fragment class
LocationAdapter locationAdapter = new LocationAdapter(getActivity(), locationList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rvLocationList.setLayoutManager(layoutManager);
rvLocationList.setAdapter(locationAdapter);
Adapter class
public class LocationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private ArrayList<LocationModel> locationlist;
private DataBaseHelper dataBaseHelper;
private OnItemClickListener onItemClickListener;
public final int EMPTY = 0;
public final int NOT_EMPTY = 1;
private String TAG = "LocationAdapter";
public LocationAdapter(Context context, ArrayList<LocationModel> list) {
this.mContext = context;
this.locationlist = list;
dataBaseHelper = new DataBaseHelper(context);
}
#Override
public int getItemViewType(int position) {
Log.d(TAG, "position = " + position);
if (locationlist.size() == 0) {
return EMPTY;
} else {
return NOT_EMPTY;
}
}
public void refreshData(ArrayList<LocationModel> tasks) {
locationlist.clear();
locationlist.addAll(tasks);
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (viewType) {
case EMPTY:
View viewItem = inflater.inflate(R.layout.no_task_layout, parent, false);
viewHolder = new EmptyViewHolder(viewItem);
break;
case NOT_EMPTY:
View viewLoading = inflater.inflate(R.layout.location_list, parent, false);
viewHolder = new NotEmptyViewHolder(viewLoading);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (getItemViewType(position)) {
case EMPTY:
EmptyViewHolder emptyViewHolder = (EmptyViewHolder) holder;
emptyViewHolder.ivNoItem.getLayoutParams().height = R.dimen._30sdp;
emptyViewHolder.ivNoItem.getLayoutParams().width = R.dimen._30sdp;
emptyViewHolder.tvNoitem.setText("No Location.");
emptyViewHolder.tvAddItem.setText("Add Location");
break;
case NOT_EMPTY:
break;
}
}
#Override
public int getItemCount() {
return locationlist == null ? 0 : locationlist.size();
}
public class NotEmptyViewHolder extends RecyclerView.ViewHolder {
private ImageView ivFirstCharecter, ivMore;
private TextView tvName, tvAddress;
NotEmptyViewHolder(View itemView) {
super(itemView);
ivFirstCharecter = itemView.findViewById(R.id.ivFirstCharecter);
ivMore = itemView.findViewById(R.id.ivMore);
tvName = itemView.findViewById(R.id.tvName);
tvAddress = itemView.findViewById(R.id.tvAddress);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.OnItemClick(locationlist.get(getAdapterPosition()).getLocationName());
}
});
}
}
public class EmptyViewHolder extends RecyclerView.ViewHolder {
private ImageView ivNoItem;
private TextView tvNoitem, tvAddItem;
EmptyViewHolder(View itemView) {
super(itemView);
ivNoItem = itemView.findViewById(R.id.ivNoItem);
tvNoitem = itemView.findViewById(R.id.tvNoitem);
tvAddItem = itemView.findViewById(R.id.tvAddItem);
}
}
public void setOnItemClickListener(OnItemClickListener itemClickListener) {
onItemClickListener = itemClickListener;
}
public interface OnItemClickListener {
void OnItemClick(String locationName);
}
}
No layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llNoTask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/ivNoItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_no_task" />
<TextView
android:id="#+id/tvNoitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/semibold"
android:textColor="#color/black"
android:textSize="#dimen/_30sdp" />
<TextView
android:id="#+id/tvAddItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/regular"
android:textColor="#color/text_gray"
android:textSize="#dimen/_18sdp" />
Fragment layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvLocationList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/_60sdp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fbtnAddLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="#dimen/_10sdp"
android:gravity="center_vertical"
app:backgroundTint="#color/Red"
app:fabSize="normal"
app:srcCompat="#drawable/ic_add" />
Home activity
fragment = new LocationFragment();
try {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
} catch (IllegalStateException ieEx) {
ieEx.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
The empty item is itself an item. To be displayed the item count must not be 0, otherwise the other methods (getItemViewType(), onCreateViewHolder(), ...) are never called.
#Override
public int getItemCount() {
return locationlist == null ? 0 : Math.max(1, locationlist.size());
}
You may also return 1 if locationlist is null but you have to handle the case in other methods :
#Override
public int getItemViewType(int position) {
Log.d(TAG, "position = " + position);
if (locationlist == null || locationlist.size() == 0) {
return EMPTY;
} else {
return NOT_EMPTY;
}
}
Include no_task_layout.xml content in Fragment layout xml, set its Visibility to "gone", Then check if locationlist is empty in Fragment Class,
if(locationList.size > 0){ ///Set adapter to Recycler view
Otherwise set rvLocationList.setVisibility(View.GONE) and show the Empty View.

TextViews not populating with data from SQLite database in RecyclerView

I'm new to Java, Android and SQLite, so quite frankly I'm amazed that I have gotten this far.
I am trying to create a simple cataloguing app for my bonsai collection which displays a summary of my collection in a RecyclerView on the MainActivity.
I've got the database working, in that I can add items to it (checked through DB Browser for SQLite). The trouble I'm having is displaying that data in the RecyclerView. Currently it is just showing the laucher icon placeholder image and not populating the TextViews with the data from the DB. The number of views that are showing in the RecyclerView correspond with the number of entries in the DB.
I'm not sure what I'm doing wrong, so any help would be greatly appreciated.
MainActivity.java
Datasource mDataSource;
Button btnAddNew;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSource = new Datasource(this);
mDataSource.open();
List<DataModel> listFromDB = mDataSource.getAllItems();
DataItemAdapter adapter = new DataItemAdapter(this, listFromDB);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvItems);
recyclerView.setAdapter(adapter);
btnAddNew = (Button) findViewById(R.id.btnInsert);
}
DataModel.Java
public class DataModel {
private String itemId;
private String itemName;
private String itemCommonName;
public DataModel() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCommonName() {
return itemCommonName;
}
public void setItemCommonName(String itemCommonName) {
this.itemCommonName = itemCommonName;
}
Datasource.java
public class Datasource {
private Context mContext;
private SQLiteDatabase mDatabase;
SQLiteOpenHelper mDbHelper;
public Datasource(Context context){
this.mContext = context;
mDbHelper = new DatabaseHelper(mContext);
mDatabase = mDbHelper.getWritableDatabase();
}
public void open(){
mDatabase = mDbHelper.getWritableDatabase();
}
public void close(){
mDatabase.close();
}
public boolean insertData(String name, String commonName, String scientificName){
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_COMMON_NAME, commonName);
contentValues.put(COL_SCI_NAME, scientificName);
long result = db.insert(DATABASE_TABLE, null, contentValues);
db.close();
if(result == -1) {
return false;
}else{
return true;
}
}
public List<DataModel> getAllItems(){
List<DataModel> dataModels = new ArrayList<>();
Cursor cursor = mDatabase.query(DATABASE_TABLE, ItemsTable.ALL_COLUMNS,
null, null, null, null, null);
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}
DataItemAdapter.java
public class DataItemAdapter extends RecyclerView.Adapter<DataItemAdapter.ViewHolder> {
private List<DataModel> mItems;
private Context mContext;
public DataItemAdapter(Context context, List<DataModel> items) {
this.mContext = context;
this.mItems = items;
}
#Override
public DataItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(DataItemAdapter.ViewHolder holder, int position) {
final DataModel item = mItems.get(position);
holder.tvName.setText(item.getItemName());
holder.tvCommonName.setText(item.getItemCommonName());
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName, tvCommonName;
public ImageView ivProfilePic;
public View mView;
public ViewHolder(View itemView){
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCommonName = (TextView) itemView.findViewById(R.id.tvCommonName);
ivProfilePic = (ImageView) itemView.findViewById(R.id.ivProfilePic);
mView = itemView;
}
}
RecyclerView object in activity_main.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/rvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"/>
TextViews and Image view list_item.xml
<ImageView
android:id="#+id/ivProfilePic"
android:layout_width="75dp"
android:layout_height="75dp"
app:srcCompat="#mipmap/ic_launcher_round"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:contentDescription="Profile Pic"
tools:ignore="HardcodedText"/>
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="19dp"
android:layout_toEndOf="#+id/ivProfilePic"
android:text="TextView"
android:textSize="18sp"
android:visibility="visible"/>
<TextView
android:id="#+id/tvCommonName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView"
android:visibility="visible"/>
Screenshot of what the MainActivity currently looks like:
Any other information required, just ask and I'll try to post it up.
Sorted it out, seems so simple now that I look at it.
In the Cursor, I hadn't changed the item setters to the correct ones after I copied and pasted the first line, just the column names.
Also I was identifying the ID column as a string, where it should have been an integer - also updated this in the DataModel class
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getInt(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemCommonName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemSciName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}

my RecyclerView does not show anything

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.

Blank ListView with BaseAdapter

I am trying to fill my list from database using BaseAdapter. Logcat don't show any error. Here is my code.
In this DatabaseHelper class, I have one table STUDENTS.
DatabaseHelper.java
public long saveData(Student std) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME",std.name);
cv.put("CITY",std.city);
cv.put("AGE",std.age);
long id = db.insert("STUDENTS", null, cv);
db.close();
return id;
}
public ArrayList<Student> getAllStudent() {
ArrayList<Student> studentArrayList = new ArrayList<Student>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query("STUDENTS",null,null,null,null,null,null);
Log.e("COUNT",""+cursor.getCount());
while (cursor.moveToNext()) {
Student s = new Student();
s.name = cursor.getString(cursor.getColumnIndex("NAME"));
s.city = cursor.getString(cursor.getColumnIndex("CITY"));
s.age = cursor.getString(cursor.getColumnIndex("AGE"));
studentArrayList.add(s);
}
db.close();
return studentArrayList;
}
MyBaseAdapter.java
public class MyBaseAdapter extends BaseAdapter {
ArrayList<Student> myList = new ArrayList<Student>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context,ArrayList<Student> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Student getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
myViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.single_row, null);
viewHolder = new myViewHolder();
convertView.setTag(viewHolder);
} else {
viewHolder = (myViewHolder) convertView.getTag();
}
viewHolder.nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.cityTextView);
viewHolder.ageTextView = (TextView) convertView.findViewById(R.id.ageTextView);
viewHolder.nameTextView.setText(myList.get(position).name);
viewHolder.cityTextView.setText(myList.get(position).city);
viewHolder.ageTextView.setText(myList.get(position).age);
return convertView;
}
public class myViewHolder {
TextView nameTextView, cityTextView, ageTextView;
}
}
This is my model class
Student.java
public class Student {
String name;
String city;
String age;
}
and in my MainActivity I am trying to fill data into list.
MainActivity.java
public class MainActivity extends ActionBarActivity {
public EditText searchEditText;
public Button addButton;
public ListView studentListView;
public DatabaseHelper dbHelper;
public ArrayList<Student> arrayList;
public MyBaseAdapter myBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchEditText = (EditText)findViewById(R.id.searchEditText);
addButton = (Button)findViewById(R.id.addButton);
studentListView = (ListView) findViewById(R.id.studentListView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AddNewStudent.class);
startActivity(i);
}
});
dbHelper = new DatabaseHelper(getApplicationContext());
arrayList = dbHelper.getAllStudent();
myBaseAdapter = new MyBaseAdapter(MainActivity.this,arrayList);
studentListView.setAdapter(myBaseAdapter);
myBaseAdapter.notifyDataSetChanged();
}
}
single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/container">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/nameTextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/cityTextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/ageTextView" />
</LinearLayout>
I don't know where I went wrong.
Finally, I have found the answer for this. You just need to add couple of line in getView() method to assign value from list to model class object.
public View getView(int position, View convertView, ViewGroup parent) {
Student std = new Student(); //this line I added
std = myList.get(position); //this line I added
myViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.single_row, null);
viewHolder = new myViewHolder();
convertView.setTag(viewHolder);
} else {
viewHolder = (myViewHolder) convertView.getTag();
}
viewHolder.nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.cityTextView);
viewHolder.ageTextView = (TextView) convertView.findViewById(R.id.ageTextView);
viewHolder.nameTextView.setText(myList.get(position).name);
viewHolder.cityTextView.setText(myList.get(position).city);
viewHolder.ageTextView.setText(myList.get(position).age);
return convertView;
}

drag-sort-listview Drag is not working Android

I'm using drag-sort-listview to sort rows of my ListView, and I have created a demo using this library, but it is not working. When I try to drag rows it is not working.
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };
public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };
public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };
//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);
//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
activity_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"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="#drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titles"
android:layout_toRightOf="#+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
RowItem.java
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Use Drag handle Id in DragSortListView tag in Xml
dslv:drag_handle_id="#id/drag_handle"
Make an id.xml file and put drag handle id as above to make it common and use the same id on dragable handle image view in your row item.
Hope it helps.

Categories

Resources