Unable to refresh RecyclerView - android

I'm new to Android programming, my problem is when update one record in another Activity from my MainActivity, the RecyclerView is not refreshed.
I have a ManinActivity with a RecyclerView, an activity_Detail for inserting and updating records and an activity_CardView to view the items stored in the database.
Here is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
rvNoteAdapter rvNoteAdapter;
private Toolbar mToolbar;
private FloatingActionButton fab;
private String rowID = null;
NoteDatabaseAdapter note_database;
FloatingActionButton btnAddNewRecord;
android.widget.LinearLayout parentLayout;
LinearLayout layoutDisplayPeople;
TextView tvNoRecordsFound;
ArrayList<create_note> notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAllWidgets();
note_database = new NoteDatabaseAdapter(MainActivity.this,6);
bindWidgetsWithEvent();
//displayAllRecords();
Recycler_do();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String note_type = data.getStringExtra(Constants.COLUMN_NOTE_TYPE);
String note_text = data.getStringExtra(Constants.COLUMN_NOTE_TEXT);
String note_id = data.getStringExtra(Constants.ID);
create_note note = new create_note();
note.setType(note_type);
note.setText(note_text);
if (requestCode == Constants.ADD_RECORD) {
//sQLiteHelper.insertRecord(firstname, lastname);
note_database.insert(note);
//recyclerAdapterNote.addItem(0,note);
} else if (requestCode == Constants.UPDATE_RECORD) {
note.setId(note_id);
//sQLiteHelper.updateRecord(firstname, lastname, rowID);
note_database.update(note);
}
Recycler_do();
}
}
private void getAllWidgets() {
btnAddNewRecord = (FloatingActionButton) findViewById(R.id.fab);
parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
layoutDisplayPeople = (LinearLayout) findViewById(R.id.layoutDisplayNote);
tvNoRecordsFound = (TextView) findViewById(R.id.tvNoRecordsFound);
recyclerView = (RecyclerView) findViewById(R.id.rvNotes);
}
public void Recycler_do ()
{
notes = note_database.getAllRecords();
LinearLayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
rvNoteAdapter adapter=new rvNoteAdapter(MainActivity.this,contacts);
recyclerView.setAdapter(adapter);
}
private void bindWidgetsWithEvent() {
btnAddNewRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddRecord();
}
});
}
private void onAddRecord() {
Intent intent = new Intent(MainActivity.this, Detail.class);
intent.putExtra(Constants.DML_TYPE, Constants.INSERT);
startActivityForResult(intent, Constants.ADD_RECORD);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
activity_Detail:
public class Detail extends AppCompatActivity {
EditText note_type;
EditText note_text;
RecyclerView recyclerView;
NoteDatabaseAdapter noteDatabaseAdapter=new NoteDatabaseAdapter(Detail.this,6);
String id;
String request="";
TextView toolbarText;
ImageView btnDML;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Detail);
getAllWidgets();
bindWidgetsWithEvent();
checkForRequest();
}
private void checkForRequest() {
request = getIntent().getExtras().get(Constants.DML_TYPE).toString();
if (request.equals(Constants.UPDATE)) {
toolbarText.setText("update");
note_text.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TEXT).toString());
note_type.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TYPE).toString());
id=getIntent().getExtras().get(Constants.ID).toString();
} else {
toolbarText.setText("new note");
}
}
private void bindWidgetsWithEvent() {
btnDML.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClick();
}
});
final ImageView back_btn = (ImageView) findViewById(R.id.back_btn);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Detail.this,"back btn",Toast.LENGTH_LONG).show();
finish(); //back to prev activity
}
});
}
private void getAllWidgets() {
note_type = (EditText) findViewById(R.id.note_type_EB);
note_text = (EditText) findViewById(R.id.note_text_EB);
toolbarText=(TextView) findViewById(R.id.toolbar_text);
btnDML = (ImageView) findViewById(R.id.save_btn);
recyclerView=(RecyclerView) findViewById(R.id.rvNotes);
setTitle(null);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
//topToolBar.setLogo(R.mipmap.ic_launcher);
// topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
}
private void onButtonClick() {
if (note_type.getText().toString().equals("") || note_text.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Add Both Fields", Toast.LENGTH_LONG).show();
} else if (request.equals(Constants.INSERT))
{
Intent intent = new Intent();
intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type.getText().toString());
intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text.getText().toString());
intent.putExtra(Constants.ID, id);
setResult(RESULT_OK, intent);
finish();
}
else if (request.equals(Constants.UPDATE))
{
create_note note = new create_note();
note.setType(note_type.getText().toString());
note.setText(note_text.getText().toString());
note.setId(id);
try {
noteDatabaseAdapter.update(note);
ArrayList<create_note> noteArrayList = noteDatabaseAdapter.getAllRecords();
ArrayList<create_note> temp=noteDatabaseAdapter.getAllRecords();
rvNoteAdapter rvNoteAdaptermodel=new rvNoteAdapter(Detail.this,temp);
**//do not refresh RecyclerView
rvNoteAdaptermodel.updateItems(noteArrayList);**
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
finish();
//
}
}
activity_CardView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:padding="5dp"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv">
<RelativeLayout
android:id="#+id/inflateParentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
>
<ImageView
android:contentDescription="#string/action_new"
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:src="#mipmap/ic_save"
/>
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_type_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
/>
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_text_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:layout_below="#+id/note_type_inflate" />
<TextView
android:layout_toRightOf="#id/back_btn"
android:id="#+id/note_id_inflate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_weight="1"
android:text="Name"
android:textSize="15sp"
android:gravity="start"
android:textColor="#color/colorPrimary"
android:layout_below="#+id/note_text_inflate" />
</RelativeLayout>
rvNoteAdapter.java (Adapter for RecyclerView)
public class rvNoteAdapter extends RecyclerView.Adapter<rvNoteAdapter.ViewHolder> {
private List<create_note> noteList= Collections.emptyList();
Context noteContext;
private create_note note;
private String rowID = null;
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView noteText;
public TextView noteType;
public TextView noteId;
private CardView cardView;
public ViewHolder(View itemView){
super(itemView);
noteText=(TextView) itemView.findViewById(R.id.note_text_inflate);
noteType=(TextView) itemView.findViewById(R.id.note_type_inflate);
noteId=(TextView) itemView.findViewById(R.id.note_id_inflate);
cardView = (CardView) itemView.findViewById(R.id.cv);
}
}
public rvNoteAdapter(Context context,List<create_note> Note_List){
this.noteList=Note_List;
this.noteContext=context;
}
private Context getNoteContext()
{
return noteContext;
}
#Override
public rvNoteAdapter.ViewHolder onCreateViewHolder (ViewGroup parent,int viewType)
{
// Context context=parent.getContext();
// LayoutInflater inflater=LayoutInflater.from(context);
//View NoteView=inflater.inflate(R.layout.activity_CardView,parent,false);
//ViewHolder viewHolder=new ViewHolder(NoteView);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_CardView, parent, false);
ViewHolder memberViewHolder = new ViewHolder(view);
return memberViewHolder;
}
#Override
public void onBindViewHolder(final rvNoteAdapter.ViewHolder viewHolder,int position)
{
//viewHolder.noteText.setText(noteList.get(position).getText());
create_note note=noteList.get(position);
viewHolder.noteText.setText(note.getText());
viewHolder.noteType.setText(note.getType());
viewHolder.noteId.setText(note.getId());
final int pos=position;
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
create_note note=(create_note)v.getTag();
String note_text=viewHolder.noteText.getText().toString();
String note_type=viewHolder.noteType.getText().toString();
String note_id=viewHolder.noteId.getText().toString();
Intent intent = new Intent(v.getContext(), Detail.class);
intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type);
intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text);
intent.putExtra(Constants.ID, note_id);
intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);
v.getContext().startActivity(intent);
// mainActivity.onUpdateRecord(note_text,"jhkhkj",note_id);
Toast.makeText(noteContext,"clicked"+pos,Toast.LENGTH_LONG).show();
}
});
}
//my problem with this code that not refreshed RecyclerView
public void updateItems(ArrayList<create_note> notes)
{
noteList.clear();
noteList.addAll(notes);
notifyDataSetChanged();
}
public void addItem(int position, create_note note) {
try {
noteList.add(position, note);
notifyItemInserted(position);
}
catch (Exception e) {
}
}
public void removeItem(create_note note) {
int position=noteList.indexOf(note);
noteList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return noteList.size();
}
NoteDatabaseAdapter.java (adapter for database) :
public class NoteDatabaseAdapter extends SQLiteOpenHelper {
public static final String TABLE_NAME = "tbl_note";
public static final String ID = "ID";
public static final String COLUMN_NOTE_TYPE = "type";
public static final String COLUMN_NOTE_TEXT = "text";
private SQLiteDatabase database;
public NoteDatabaseAdapter(Context context,int newVersion) {
super(context,"noteDatabase.db",null,newVersion);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
String sql = "create table "+ TABLE_NAME + " ( id integer primary key autoincrement NOT NULL," + COLUMN_NOTE_TYPE + " NVARCHAR," + COLUMN_NOTE_TEXT + " NVARCHAR)";
db.execSQL(sql);
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
try{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}catch (Exception e)
{
Log.d("Database", "Exception:" + e.getMessage());
}
}
public void insert(create_note note) {
try {
database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NOTE_TYPE, note.getType());
contentValues.put(COLUMN_NOTE_TEXT, note.getText());
database.insert(TABLE_NAME, null, contentValues);
database.close();
} catch (Exception e) {
Log.d("Database", "Exception:" + e.getMessage());
}
}
public void update(create_note note) {
try {
database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NOTE_TYPE, note.getType());
contentValues.put(COLUMN_NOTE_TEXT, note.getText());
database.update(TABLE_NAME,contentValues,"id="+note.getId(),null);
database.close();
} catch (Exception e) {
Log.d("Database", "Exception:" + e.getMessage());
}
}
public ArrayList<create_note> getAllRecords() {
database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);
ArrayList<create_note> notes = new ArrayList<create_note>();
create_note note_model;
cursor.moveToLast();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
note_model = new create_note();
note_model.setId( cursor.getString(0));
note_model.setType(cursor.getString(1));
note_model.setText(cursor.getString(2));
notes.add(note_model);
cursor.moveToPrevious();
}
}
cursor.close();
database.close();
return notes;
}
}
create_note.java (object class)
public class create_note {
private String id;
private String type;
private String text;
public create_note(){}
public create_note(String type, String text) {
this.type = type;
this.text = text;
}
public create_note(String id, String type, String text) {
this.id = id;
this.type = type;
this.text = text;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setType(String type) {
this.type = type;
}
}
My problem is in rvNoteAdapter.java on UpdateItem method.
adapter.invalidate is not working,
Can anybody help me?

Use this to set and refresh apter of recyclerview.
if (null == rvNoteAdapter) {
rvNoteAdapter rvNoteAdaptermodel=new
rvNoteAdapter(Detail.this,temp);
rvNoteAdaptermodel.updateItems(noteArrayList);
recyclerView.setAdapter(adapter);
} else {
rvNoteAdaptermodel.updateItems(noteArrayList);
rvNoteAdapter.notifyDataSetChanged();
}
And your updateItemsmethod should be like,
public void updateItems(ArrayList<create_note> notes)
{
noteList.clear();
noteList.addAll(notes);
}

i use this method to update Recyclerview
in MainActivity
set notes ArreyList as static
set rvNotAdapter as static
then i use this variables in DetailActivity.
in DetailActivity use this code :
ArreyList<create_note> noteArreyList = noteDatabaseAdapter.getAllRecords();
MainActivity.notes.clear();
MainActivity.notes.addAll(noteArreyList);
MainActivity.rvNoteAdapter.notifyDataSetChanged();
i use this codes after i updete my data in database :
noteDatabaseAdapter.update(note);

Related

How to pass Recycler View Items into one TextView

I am trying to get a TextView value item within the RecyclerView. My RecyclerView layout file has two TextViews, one is Product Name and the other for the Quantity as you can see here
=== This is my cart_items_layout_item ===
<TextView
android:id="#+id/cart_list_product_name"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Name"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginLeft="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/cart_list_product_quantity"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Quantity"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:gravity="end"
android:textStyle="bold"/>
This is my activity_cart xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cart_list"
android:layout_width="match_parent"
android:layout_height="542dp"
android:layout_above="#+id/next"
android:layout_below="#id/header_color"
android:layout_marginBottom="113dp">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/button"
android:text="CONFIRM ORDER/S"
android:textColor="#color/colorPrimaryDark"
android:layout_margin="10dp" />
<Button
android:id="#+id/sendSMSButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="69dp"
android:background="#drawable/button"
android:text="Send"
android:textColor="#color/colorPrimaryDark" />
<TextView
android:id="#+id/smsphoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cart_list"
android:text="0918"/>
This is my RecyclerView Adapter Class
#Override
protected void onStart() {
super.onStart();
final DatabaseReference cartListRef =
FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products"), Cart.class)
.build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter =
new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder
holder, int i, #NonNull final Cart model) {
holder.txtProductName.setText(model.getProductName());
holder.txtProductQuantity.setText("Quantity = " +
model.getQuantity());
holder.itemView.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Removed"
};
AlertDialog.Builder builder = new
AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface
dialogInterface, int i)
{
if (i == 0)
{
Intent intent = new
Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid",model.getPid());
startActivity(intent);
}
if(i == 1)
{
cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull
Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent = new
Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
if(i == 1)
{
cartListRef.child("Admin View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void
onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent =
new Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout,
parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
=== this is my Cart class/Model ===
public class Cart
{
private String
date,discount,pid,productDesc,productName,productSupplier,quantity,time;
public Cart()
{
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductSupplier() {
return productSupplier;
}
public void setProductSupplier(String productSupplier) {
this.productSupplier = productSupplier;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Cart(String date, String discount, String pid, String productDesc,
String productName, String productSupplier, String quantity, String time)
{
this.date = date;
this.discount = discount;
this.pid = pid;
this.productDesc = productDesc;
this.productName = productName;
this.productSupplier = productSupplier;
this.quantity = quantity;
this.time = time;
}
=== CartViewHolder ===
public class CartViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
public TextView txtProductName, txtProductQuantity;
private ItemClickListener itemClickListener;
public CartViewHolder(#NonNull View itemView) {
super(itemView);
txtProductName = itemView.findViewById(R.id.cart_list_product_name);
txtProductQuantity =
itemView.findViewById(R.id.cart_list_product_quantity);
}
#Override
public void onClick(View view)
{
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
}
As you can see in this Image, i use the cart class/model to pass the data to them, then i created another class called CartViewHolder i use this class to set the data into Recycler View. i want to get this values and put it in the message particularly in the SMS. i dont know how to pass it i tried several codes for it.
private void sendSmsBySIntent ()
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra("PUT THE ITEMS HERE");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
you can use your List<Cart> cart model list item to send product and quantity to
sms.
private void sendSmsBySIntent (Cart model)
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
smsSIntent.putExtra("pName",model.getProductName());
smsSIntent.putExtra("pQty",model.getQuantity());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
You need the list you sent to the adapter. Send it as a parameter to the sendSmsBySIntent() function and make a for loop where you build a String.
ie.:
private void sendSmsBySIntent (List<Cart> yourList){
StringBuilder extra = new StringBuilder();
for (int i = 0; i < yourList.size(); i++) {
//Build the string the way you want
extra.append(yourList.get(i).getName()).append(" ").append(yourList.get(i).getQuantity);
}
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra(extra.toString());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
Edit:
I changed the function inside () , check it.
Now, when you call the function you have to pass the list you are working with. Like so: sendSmsBySIntent(placeHereYourCartList)

Recyclerview - Clicking on results displayed by search opens incorrect item

I'm having a recyclerview to display a list of notes from room database. I've also added search functionality. Currently, I'm having 4 notes in MainActivity (this activity displays notes). On searching, if I get resultant list having more than 2 notes, on clicking them it displays correct notes.But, if resultant has 1 or 2 notes, it always displays the first 2 in list, not the notes filtered by search.
Here's my code:
Model class Note:
#Entity(tableName = TABLE_NAME)
public class Note implements Serializable{
#Nullable
private int Color;
#PrimaryKey(autoGenerate = true)
private long id;
/** Not-null value. */
private String Desc;
private String Time;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public Note() {
}
public Note(String Desc, String Time) {
this.Desc = Desc;
this.Time = Time;
}
public int getColor() {
return Color;
}
public void setColor(int color) {
Color = color;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
/** Not-null value. */
public String getDesc() {
return Desc;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setDesc(String Desc) {
this.Desc = Desc;
}
public String getTime() {
return Time;
}
public void setTime(String Time) {
this.Time = Time;
}
NotesAdapter:
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyViewHolder> {
public List<Note> list;
private Context context;
private List<Note> filteredList = new ArrayList<>();
private ClickListener clickListener;
public List<Note> selectednotes_list = new ArrayList<>();
private String TAG = NotesAdapter.class.getSimpleName();
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mNoteDesc;
public TextView mNoteTime;
public RelativeLayout mcontainer;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNoteTime = itemView.findViewById(R.id.note_time);
mNoteDesc = itemView.findViewById(R.id.note_desc);
mcontainer = itemView.findViewById(R.id.note_container);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,this.getLayoutPosition());
}
/*
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
clickListener.onClick(v,getLayoutPosition());
//clickListener.onClick(filteredList.get(getAdapterPosition()));
}
*/
}
public NotesAdapter(List<Note> list, Context context,List<Note> selectednotes_list) {
this.list = list;
this.filteredList = list;
this.context = context;
this.selectednotes_list = selectednotes_list;
this.clickListener = (ClickListener) context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.noteview,null,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.mNoteTime.setText(list.get(position).getTime());
holder.mcontainer.setBackgroundColor(Utils.getRandomMaterialColor(context, "50to300"));
holder.mNoteDesc.setText(list.get(position).getDesc());
// Change background color on select
if (selectednotes_list.size() > 0) {
if (selectednotes_list.contains(list.get(position)))
holder.mcontainer.setBackgroundColor(ContextCompat.getColor(context, R.color.colorSecondary));
}
}
#Override
public int getItemCount() {
return list.size();
}
public void filterList(List<Note> filter) {
this.list = filter;
notifyDataSetChanged();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ClickListener{
private StaggeredGridLayoutManager gridLayoutManager;
private RecyclerView recyclerView;
private List<Note> noteList, multiSelectList;
public NotesAdapter notesAdapter;
private Notedatabase notedatabase;
private String TAG = MainActivity.class.getSimpleName();
private FloatingActionButton maddbtn;
private int position;
private SearchView mSearchView;
private boolean isMultiSelect = false;
private Menu context_menu;
private ActionMode mActionMode;
private CoordinatorLayout mCoordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
displayList();
/*
notesList.addAll(noteList);
List<Note> notesList = getNotes();
notesAdapter = new NotesAdapter(notesList,MainActivity.this);
recyclerView.setAdapter(notesAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
// Searchable config with searchview
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
mSearchView.setMaxWidth(Integer.MAX_VALUE);
// Set Listener
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter when query is submitted
Log.d(TAG, "onQueryTextSubmit: " + query);
notesAdapter.filterList(filter(query,noteList));
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// filter progressively as query changes
Log.d(TAG, "onQueryTextChange: " + newText);
notesAdapter.filterList(filter(newText,noteList));
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_search) {
// search action
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close searchview
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
return;
}
super.onBackPressed();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if (resultCode == 1) {
Log.d(TAG, "Request code is 1");
noteList.add((Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 2) {
Log.d(TAG, "Request code 2, update return");
noteList.set(position, (Note) data.getSerializableExtra("note"));
notesAdapter.notifyDataSetChanged();
}
else if(resultCode == 3) {
Log.d(TAG, "Request code 3, delete return");
Log.d(TAG, "Deleting this from list:" + (Note) data.getSerializableExtra("note"));
noteList.remove(MainActivity.this.position);
notesAdapter.notifyItemRemoved(MainActivity.this.position);
}
}
}
private void displayList() {
notedatabase = Notedatabase.getInstance(MainActivity.this);
new RetrieveTask(this).execute();
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerview);
gridLayoutManager = new StaggeredGridLayoutManager(2,1);
mCoordinatorLayout = findViewById(R.id.coordinatorLayout);
recyclerView.setLayoutManager(gridLayoutManager);
noteList = new ArrayList<>();
multiSelectList = new ArrayList<>();
notesAdapter = new NotesAdapter(noteList,MainActivity.this,multiSelectList);
recyclerView.setAdapter(notesAdapter);
maddbtn = findViewById(R.id.add_fab);
maddbtn.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
startActivityForResult(intent,REQUEST_CODE);
});
}
#Override
public void onClick(View view, int pos) {
/*
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",noteList.get(position));
Log.d(TAG, "list.get(position): " + noteList.get(pos).getDesc());
startActivityForResult(intent,REQUEST_CODE);
*/
}
#Override
public void onClick(Note note) {
/*
Log.d(TAG, "onClick with args as note1");
Intent intent = new Intent(MainActivity.this,NoteActivity.class);
intent.putExtra("note",note);
startActivityForResult(intent,REQUEST_CODE);*/
}
#Override
public void onLongClick(View view, int pos) {
/* Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);*/
}
private void multi_select(int pos) {
if(mActionMode != null) {
if(multiSelectList.contains(noteList.get(pos))) {
Log.d(TAG, "multi_select removed: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.remove(noteList.get(pos));
}
else {
Log.d(TAG, "multi_select added: " + multiSelectList.contains(noteList.get(pos)));
multiSelectList.add(noteList.get(pos));
}
if(multiSelectList.size() > 0) mActionMode.setTitle("" + multiSelectList.size() + " selected");
else mActionMode.setTitle("");
refreshAdapter();
}
}
private void refreshAdapter() {
notesAdapter.selectednotes_list = multiSelectList;
notesAdapter.list = noteList;
notesAdapter.notifyDataSetChanged();
}
class RetrieveTask extends AsyncTask<Void,Void,List<Note>>{
private WeakReference<MainActivity> weakReference;
public RetrieveTask(MainActivity mainActivity) {
weakReference = new WeakReference<>(mainActivity);
}
#Override
protected List<Note> doInBackground(Void... voids) {
if(weakReference.get()!=null)
return weakReference.get().notedatabase.getNoteDao().getNotes();
else
return null;
}
#Override
protected void onPostExecute(List<Note> notes) {
if(notes!=null & notes.size()>0) {
weakReference.get().noteList = notes;
//weakReference.get().noteList.addAll(weakReference.get().getNotes());
Log.d(TAG, "Result: " + notes);
weakReference.get().notesAdapter = new NotesAdapter(notes,weakReference.get(),multiSelectList);
/*
// Randomly set note background
for(Note n:notes) {
n.setColor(getRandomMaterialColor(MainActivity.this,"500"));
}
*/ weakReference.get().recyclerView.addOnItemTouchListener(new RecyclerTouchListener(recyclerView, getApplicationContext(), new ClickListener() {
#Override
public void onClick(View view, int pos) {
if (isMultiSelect)
multi_select(pos);
else {
Log.d(TAG, "Recylerview item onClick: ");
MainActivity.this.position = pos;
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", noteList.get(position));
Log.d(TAG, "list.get(position): " + weakReference.get().noteList.get(position).getDesc());
startActivityForResult(intent, REQUEST_CODE);
}
}
#Override
public void onClick(Note note) {
Log.d(TAG, "onClick with args as note");
Intent intent = new Intent(MainActivity.this, NoteActivity.class);
intent.putExtra("note", note);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
public void onLongClick(View view, int pos) {
Log.d(TAG, "onLongClick ");
if(!isMultiSelect) {
multiSelectList = new ArrayList<Note>();
isMultiSelect = true;
if(mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(pos);
}
}));
weakReference.get().recyclerView.setAdapter(weakReference.get().notesAdapter);
weakReference.get().notesAdapter.notifyDataSetChanged();
}
else{
displayErrorMsg();
}
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//Prepare the menu
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action,menu);
context_menu = menu;
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//mode.getCustomView().setBackgroundColor(getApplicationContext().getResources().getColor(android.R.color.white));
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// display alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Delete " + multiSelectList.size() + " notes?");
builder.setCancelable(true);
builder.setPositiveButton(R.string.alert_yes,(dialog, which) -> {
// Deleting notes
for (int i = 0; i < multiSelectList.size(); i++) {
Log.d(TAG, "Deleting: " + multiSelectList.get(i));
notedatabase.getNoteDao().deleteNotes(multiSelectList.get(i));
noteList.remove(multiSelectList.get(i));
}
// Display Snackbar
displaySnackbar(mCoordinatorLayout,R.string.delete_success);
dialog.cancel();
// Refresh adapter
refreshAdapter();
// dismiss the contextual action bar
if(mActionMode!=null) mActionMode.finish();
});
builder.setNegativeButton(R.string.alert_no,(dialog, which) -> {
dialog.cancel();
if(mActionMode!=null) mActionMode.finish();
});
builder.setOnCancelListener(dialog1 -> {
Log.d(TAG, "onCancelListener: ");
if(mActionMode!=null) mActionMode.finish();
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
isMultiSelect = false;
multiSelectList = new ArrayList<Note>();
refreshAdapter();
}
};
#Override
protected void onDestroy() {
notedatabase.cleanUp();
super.onDestroy();
}
private void displayErrorMsg() {
Toast.makeText(MainActivity.this,R.string.failure_display,Toast.LENGTH_SHORT).show();
}
}
Any help is widely appreciated!!
Please! Badly stuck here
Found it out!
I was not storing the result of filter, instead I was directly calling it in filterList.
noteList = filter(newText, noteList);
notesAdapter.filterList(noteList);
The above lines did it for me!

SearchView doesn't work with RecyclerView & SQLite

I have a Fragment with a RecyclerView. users input data and they will store in a SQLite DataBase. i am trying to Search in the items of this RecyclerView but it does not work,
here is my Fragment :
public class FragmentOne extends Fragment {
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private SearchView sv;
private ArrayList<Detail> mDetails=new ArrayList<>();
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView) view.findViewById(R.id.detail_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true); //This will reverse the data order but not scroll the RecyclerView to the last item
layoutManager.setStackFromEnd(true); //For keeping data order same and simply scrolling the RecyclerView to the last item
mDetailRecyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null) {
mNumberVisible =
savedInstanceState.getBoolean(SAVED_NUMBER_VISIBLE);
}
sv = (SearchView) view.findViewById(R.id.sv);
mAdapter = new DetailAdapter(mDetails);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit (String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
getDetailsSearch(query);
return false;
}
});
initViews();
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
..
..
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
// private TextView mDateTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate());
}
#Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent);
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
private Detail mDetail;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
#Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
#Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(final List<Detail> details) {
mDetails = details;
}
..
..
}
public void initViews(){
mDetailRecyclerView.setAdapter(mAdapter);
initSwipe();
}
..
..
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
DBAdapter db = new DBAdapter(getActivity());
db.openDB();
Detail p = null;
Cursor c = db.retrieve(searchTerm);
while (c.moveToNext()) {
String title = c.getString(2);
p = new Detail();
p.setTitle(title);
mDetails.add(p);
}
db.closeDB();
mDetailRecyclerView.setAdapter(mAdapter);
}
}
and this is my Database Adapter:
public class DBAdapter {
Context c;
SQLiteDatabase db;
DetailBaseHelper helper;
public DBAdapter (Context c) {
this.c = c;
helper = new DetailBaseHelper(c);
}
public void openDB() {
try {
db = helper.getWritableDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeDB() {
try {
helper.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Cursor retrieve (String searchTerm) {
String[] columns = {
"_id",
"uuid",
"title",
"des",
"date",
"rate"
Cursor c = null;
if (searchTerm != null && searchTerm.length()>0) {
String sql ="SELECT * FROM " +DetailDbSchema.DetailTable.NAME+
" WHERE "+DetailDbSchema.DetailTable.Cols.TITLE+
" LIKE '%"+searchTerm+"%'";
c = db.rawQuery(sql, null);
return c;
}
c = db.query(DetailDbSchema.DetailTable.NAME, columns,
null, null, null, null, null);
return c;
}
}
and here is DataBase Helper:
public class DetailBaseHelper extends SQLiteOpenHelper{
private static final int VERSION = 1;
private static final String DATABASE_NAME = "detailBase.db";
public DetailBaseHelper (Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL("create table " + DetailTable.NAME +
"(" +
" _id integer primary key autoincrement," +
DetailTable.Cols.UUID + ", " +
DetailTable.Cols.TITLE + ", " +
DetailTable.Cols.DES + ", " +
DetailTable.Cols.DATE + ", " +
DetailTable.Cols.RATE +
")"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,
int oldVersion, int newVersion) {
}
}
here is the tutorial that i used for this,
I'll be appreciate if u have any idea for helping me.
I think that the main problem is here you're changing the adapter, but the new adapter was never modified by the data of the results, and also you have to notify your recycler that the data set changed. so
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
/// the loop wiith the cursor
/// change the dataset
mAdapter = new DetailAdapter(mDetails);
mDetailRecyclerView.setAdapter(mAdapter);
/// tell the recycler there is a different data to display
mDetailRecyclerView.notifyDataSetChanged();
}

Change the Icon of a Button in a Recycler View in Adapter Class Based off boolean value

I'm trying to change the icon of a button in my recycler view every time the activity starts based off a boolean value in my custom object. I assume this has to be done within the adapter since not every groups button will have the same background.
Below is the code for my recycler view adapter:
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mRecipeTextSection.setOnClickListener(this);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
Toast.makeText(v.getContext(), recipeToGrocery.getRecipeName() + " added to grocery list.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v){
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I know how to change the background of the button when it's clicked with
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
but it's obviously not going to save the state of that button when the activity restarts. I'm just not sure of how to check the boolean value for each group upon activity start up and change the button background accordingly.
I tried using
if(recipe.isInList()){
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
in the onBindViewHolder method but it didn't do anything, and I'm pretty sure that wouldn't be the correct place for it anyways. I know the boolean is working properly since I use it in other places and it works fine.
Here's the relevant XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/android"
android:layout_margin="7dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:id="#+id/recycled_item_section_view"
android:elevation="30dp"
android:background="#drawable/background_border"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Recipe name"
android:textSize="24dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_recipe_name"
android:paddingBottom="3dp"
android:maxWidth="275dip"
android:singleLine="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_below="#id/recipe_list_recycler_view_recipe_name"
android:id="#+id/recipe_list_recycler_view_serving_size"
android:paddingBottom="3dp"/>
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#mipmap/ic_playlist_add_black_24dp"
android:height="36dp"
android:padding="8dp"
android:layout_alignParentRight="true"
android:id="#+id/add_to_grocery_list"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_serving_size"
android:layout_alignParentLeft="true"
android:textSize="18dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_prep_time"
android:paddingBottom="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_prep_time"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:id="#+id/recipe_list_recycler_view_cook_time"/>
</RelativeLayout>
Recipe class:
public class Recipe implements Parcelable {
//These are all of the qualities a recipe contains, we will create an arraylist of this in the activity
private String mRecipeName;
private int mID;
private String mServings;
private String mPrepTime;
private String mCookTime;
private boolean isInList;
private List<String> mIngredients;
private List<String> mDirections;
public Recipe(){
}
public Recipe(int id, String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mID = id;
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public Recipe(String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public String getRecipeName() {
return mRecipeName;
}
public int getID() {
return mID;
}
public void setID(int id){
mID = id;
}
public String getServings() {
return mServings;
}
public String getPrepTime() {
return mPrepTime;
}
public void setRecipeName(String recipeName) {
mRecipeName = recipeName;
}
public void setServingSize(String servings) {
mServings = servings;
}
public void setPrepTime(String prepTime) {
mPrepTime = prepTime;
}
public void setServings(String servings) {
mServings = servings;
}
public List<String> getIngredients() {
return mIngredients;
}
public List<String> getDirections() {
return mDirections;
}
public String getCookTime() {
return mCookTime;
}
public void setCookTime(String cookTime) {
mCookTime = cookTime;
}
public void setIngredients(List<String> ingredients) {
mIngredients = ingredients;
}
public void setDirections(List<String> directions) {
mDirections = directions;
}
public boolean isInList() {
return isInList;
}
public void setInList(boolean inList) {
isInList = inList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mRecipeName);
dest.writeInt(this.mID);
dest.writeString(this.mServings);
dest.writeString(this.mPrepTime);
dest.writeString(this.mCookTime);
dest.writeByte(this.isInList ? (byte) 1 : (byte) 0);
dest.writeStringList(this.mIngredients);
dest.writeStringList(this.mDirections);
}
protected Recipe(Parcel in) {
this.mRecipeName = in.readString();
this.mID = in.readInt();
this.mServings = in.readString();
this.mPrepTime = in.readString();
this.mCookTime = in.readString();
this.isInList = in.readByte() != 0;
this.mIngredients = in.createStringArrayList();
this.mDirections = in.createStringArrayList();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel source) {
return new Recipe(source);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
And main activity class that uses the adapter:
public class RecipeList extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int REQUEST_CODE=1;
private Button mNavigateGroceryButton;
RecipeDB dbHelper = new RecipeDB(this);
List<Recipe> recipes;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = dbHelper.getAllRecipes();
setContentView(R.layout.activity_recipe_list);
mRecyclerView = (RecyclerView) findViewById(R.id.list_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
mNavigateGroceryButton = (Button) findViewById(R.id.navigate_to_groceries_button_list_view);
mNavigateGroceryButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(RecipeList.this, ExpandableListViewActivity.class);
//Log.d("Navigate", "navigate pressed" );
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
}
public boolean onOptionsItemSelected(MenuItem item){
//Handles menu buttons
switch (item.getItemId()){
case R.id.recipe_list_add_recipe_actionbar_button:
//This button creates a new empty Recipe object and passes it to the EditRecipe class
//The Recipe object is passed as a parcelable
Recipe passedRecipe = new Recipe();
Intent i = new Intent(RecipeList.this, EditRecipe.class);
i.putExtra("passed_recipe_key", (Parcelable) passedRecipe);
startActivityForResult(i, REQUEST_CODE);
return true;
default:
Log.d("Name,", "default called");
return super.onOptionsItemSelected(item);
}
}
public void addNewReRecipe(Recipe recipe){
dbHelper.addRecipe(recipe);
recipes = dbHelper.getAllRecipes();
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
}
//Makes the menu bar appear as it is in the action_bar_recipe_list_buttons menu layout file
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_recipe_list_buttons, menu);
return true;
}
//This code is called after creating a new recipe. This is only for creating, and not editing.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
Recipe createdRecipe = data.getExtras().getParcelable("recipe_key");
addNewReRecipe(createdRecipe);
}
}
}
}
Looks like you need to declare your button at the top of your ViewHolder with your other views. So move the declaration from the top of your adapter:
private Button mAddToGroceriesButton;
Then in your onBindViewHolder method you can get a reference to your button through the holder and set the background:
if(recipe.isInList()) {
holder.mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
Try this,
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
mRecipeTextSection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
});
Recipe recipeToGrocery = mRecipeSet.get(position);
if(!recipeToGrocery.isInList()) {
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
else{
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_26dp);//set another image
}
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
notifyDataSetChanged();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}

RecyclerView with SearchView will not populate upon initialization

I am currently using searchView to filter results on a RecyclerView. The problem is when the fragment is initialized, the list won't appear not until I click on the search icon on the toolbar and type some texts on it. I've tried modifying the codes. Take a look specifically at the adapter and holder classes, if you'll try to exchange my current codes to these:
public MembershipActivationAdapter(Context context, List<Member> members){
this.context = context;
this.mMembers = members;
}
and
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
,it will show the list upon calling the fragment however if I'll type something on the SearchView, it seems to function only as a one way filter. It will filter names but whenever I'll try to remove a character or a text on the searchview, it won't show the list back. Please help me with this. These are my codes:
Adapter & ViewHolder class:
public class MembershipActivationAdapter extends RecyclerView.Adapter<MembershipActivationAdapter.MembershipActivationViewHolder> {
private final List<Member> mMembers;
private final LayoutInflater inflater;
//private final Context context;
public MembershipActivationAdapter(Context context, List<Member> members){
inflater = LayoutInflater.from(context);
mMembers = new ArrayList<>(members);
//this.context = context;
//this.mMembers = members;
}
#Override
public int getItemCount() {
return mMembers.size();
}
#Override
public void onBindViewHolder(MembershipActivationViewHolder holder, final int position) {
final Member m = mMembers.get(position);
holder.name.setText(m.getName());
holder.email.setText(m.getEmail());
if(m.getStatus().equals("Active")){
holder.status.setText(Html.fromHtml("<font color='#00CD00'>" + m.getStatus() + "</font>"));
}else{
holder.status.setText(Html.fromHtml("<font color='#ff0000'>" + m.getStatus() + "</font>"));
}
}
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = inflater.inflate(R.layout.member_activation_content, viewGroup, false);
return new MembershipActivationViewHolder(itemView);
//final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
public static class MembershipActivationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView name;
public final TextView email;
public final TextView status;
public MembershipActivationViewHolder(View v) {
super(v);
v.setOnClickListener(this);
name = (TextView) v.findViewById(R.id.member_name);
email = (TextView) v.findViewById(R.id.member_email);
status = (TextView) v.findViewById(R.id.member_status);
}
}
public List<Member> getMemberList() {
return mMembers;
}
public void animateTo(List<Member> members) {
applyAndAnimateRemovals(members);
applyAndAnimateAdditions(members);
applyAndAnimateMovedItems(members);
}
private void applyAndAnimateRemovals(List<Member> newMembers) {
for (int i = mMembers.size() - 1; i >= 0; i--) {
final Member member = mMembers.get(i);
if (!newMembers.contains(member)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Member> newMembers) {
for (int i = 0, count = newMembers.size(); i < count; i++) {
final Member member = newMembers.get(i);
if (!mMembers.contains(member)) {
addItem(i, member);
}
}
}
private void applyAndAnimateMovedItems(List<Member> newMembers) {
for (int toPosition = newMembers.size() - 1; toPosition >= 0; toPosition--) {
final Member member = newMembers.get(toPosition);
final int fromPosition = mMembers.indexOf(member);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Member removeItem(int position) {
final Member member = mMembers.remove(position);
notifyItemRemoved(position);
return member;
}
public void addItem(int position, Member member) {
mMembers.add(position, member);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Member member = mMembers.remove(fromPosition);
mMembers.add(toPosition, member);
notifyItemMoved(fromPosition, toPosition);
}
}
Fragment Class:
public class MembershipActivationFragment extends Fragment implements SearchView.OnQueryTextListener{
private static String url = "http://www.xxxxx.org/portal/webservices/get_members.php";
private List<Member> memberList;
private RecyclerView recyclerView;
private MembershipActivationAdapter adapter;
private String pid;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_activation, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.members_recycler_view);
setHasOptionsMenu(true);
memberList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
populate();
return rootView;
}
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
String name, email, status;
Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
member = new Member(name, email, status);
memberList.add(member);
} catch (Exception e) {
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
adapter = new MembershipActivationAdapter(getActivity(), memberList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<Member> filteredMemberList = filter(memberList, query);
adapter.animateTo(filteredMemberList);
recyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Member> filter(List<Member> members, String query) {
query = query.toLowerCase();
final List<Member> filteredModelList = new ArrayList<>();
for (Member member : members) {
final String text = member.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(member);
}
}
return filteredModelList;
}
private void hidePDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
RecyclerView container 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">
<android.support.v7.widget.RecyclerView
android:id="#+id/members_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Content class:
<?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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name here"
android:textStyle="bold"
android:id="#+id/member_name"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_email"
android:layout_below="#+id/member_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_status"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
Model Class:
public class Member {
private String name;
private String email;
private String status;
public Member(String name, String email, String status) {
this.name = name;
this.email = email;
this.status = status;
}
public Member(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Atlast! I was able to find the resolution for this. Kudos to the developer himself, Xaver Kapeller!
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
// hidePDialog();
String email, status;
// Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
final String name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
mModels.add(new ExampleModel(name));
// member = new Member(name, email, status);
} catch (Exception e) {
}
}
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
Just tranfer these two lines of code inside onResponse() and everything will work perfectly fine:
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);

Categories

Resources