I have an activity that is separated into two sections:
This first one is a Relative layout, in which I have a TextView that displays the total amount based on data stored on the database.
The second part is a RecyclerView, which displays all the records.
On the adapter I can update and delete the information from the database and I use notifyItemRemoved(position) and notifyItemChanged(position) to reflect the change on the reclyclerview.
My problem is that I couldn't find a way to update the TextView on the Relative Layout, I tried to use notifyDataSetChanged() on the Activity but it doesn't reload the list with the sum of values from the database. If I use it from the adapter I couldn't find a way to access the TextView on the activity. I also tried to set an observer on the adapter, but it doesn't reflect the changes.
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
tripRecordList = getStandardAmountList(tripRecordList);
Collections.reverse(tripRecordList);
mAmount.setText(String.valueOf(nf.format(getAmountStd(tripRecordList))));
}
}
});
Following are the code fragments.
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".Activities.ViewTripRecord">
<RelativeLayout
android:id="#+id/viewrecordLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/viewrecordSummaryText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="#dimen/cardview_compat_inset_shadow"
android:gravity="center"
android:text="#string/trip_summary"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp" />
<TextView
android:id="#+id/viewrecordTotalAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/viewrecordSummaryText"
android:layout_alignParentStart="true"
android:padding="3dp"
android:text="#string/amount"
android:textSize="15sp"
android:textStyle="italic|bold" />
<TextView
android:id="#+id/viewrecordTotalAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/viewrecordSummaryText"
android:layout_alignParentStart="true"
android:layout_marginStart="95dp"
android:padding="3dp"
android:textSize="15sp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/viewrecordRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/viewrecordTotalAmountText"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_trip_record);
setTitle(getResources().getString(R.string.view_expenses));
dbHandler = new DbHandler(this);
tripID = getIntent().getIntExtra("TripID",0);
tripRecordList = dbHandler.getTripRecords(tripID);
mAmount = findViewById(R.id.viewrecordTotalAmount);
recyclerView = findViewById(R.id.viewrecordRecyclerView);
setLayout();
}
private void setLayout(){
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
if(tripRecordList.size()>0) {
tripRecordList = getStandardAmountList(tripRecordList);
Collections.reverse(tripRecordList);
mAmount.setText(String.valueOf(nf.format(getAmountStd(tripRecordList))));
}
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ViewTripRecordAdapter(tripRecordList, this);
recyclerView.setAdapter(adapter);
}
Adpater:
public class TripRecordView extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView stdAmount;
private ImageButton infoButton, deleteButton, updateButton;
public TripRecordView(#NonNull View itemView) {
super(itemView);
stdAmount = itemView.findViewById(R.id.viewtriptrecordStdAmount);
deleteButton = itemView.findViewById(R.id.viewtriptrecordDelete);
deleteButton.setOnClickListener(this);
updateButton = itemView.findViewById(R.id.viewtriptrecordUpdateButton);
updateButton.setOnClickListener(this);
}
#Override
public void onClick(final View v) {
final int position = getAdapterPosition();
switch (v.getId()){
case R.id.viewtriptrecordDelete:
deleteRecord(tripRecord2,position);
break;
case R.id.viewtriptrecordUpdateButton:
updateRecord(tripRecord2,position,recordView );
break;
}
}
}
public void deleteRecord(TripRecord deletedRecord, int position){
dbHandler = new DbHandler(context);
dbHandler.deleteTripRecord(deletedRecord.getTripID(),deletedRecord.getId());
tripRecordList.remove(position);
notifyItemRemoved(position);
}
public void updateRecord(final TripRecord updatedRecord, final int position, final View view){
EditText mAmount;
mAmount = view.findViewById(R.id.insertrecordAmount);
updatedRecord.setAmount(Double.valueOf(mAmount.getText().toString()));
dbHandler.updateTripRecord(updatedRecord);
notifyItemChanged(position);
}
Thanks,
Odair
Related
I'm trying to put a RecyclerView inside a CardView and create items dynamically.
Obviously, in XML, RecyclerView is set inside CardView tag, but as you can see picture, RecyclerView item is created outside CardView.
(RecyclerView's items are the parts expressed as kg and set in the photo. And CardView is also an item of another RecyclerView.)
What's the problem?
XML
<androidx.cardview.widget.CardView
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="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
app:cardElevation="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/workout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="TEST"/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/light_blue_400"/>
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/ll1">
<com.google.android.material.button.MaterialButton
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
style="#style/RoutineButtonStyle"
android:text="DELETE"
app:icon="#drawable/ic_delete"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
style="#style/RoutineButtonStyle"
android:text="ADD"
app:icon="#drawable/ic_add"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/ll2"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Let me know if you need any other code.
Here is the Activity of your add/delete CardView:
//Item List if you want to add one or more Items
private List<MyItem> myItems = new ArrayList<>();
private Adapter smallCardAdapter;
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv);
//Creates a new Object in the Adapter.class
smallCardAdapter = new Adapter();
recyclerView.setAdapter(smallCardAdapter);
CardView cardView = findViewById(R.id.cardView);
MaterialButton delete = findViewById(R.id.delete);
MaterialButton add = findViewById(R.id.add);
//Add onClickListener
add.setOnClickListener(v -> {
try {
size = myItems.size();
//if the value is 0, a new item is created
//if you want to delete the card after 0 than you have to change the value to 0
if(size == 0){
//Creates a new Object in the MyItem.class
myItems.add(new MyItem("Set","1kg"));
}else{
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
value++;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Add Button OnClickListener");
e.printStackTrace();
}
});
//Delete onClickListener
delete.setOnClickListener(v->{
try {
size = myItems.size();
//If the value is 0 then canceled to avoid errors
if(size == 0){
return;
}
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
//if the value is one or lower
if(value <= 1){
//The card will deleted after updateAdapter();
myItems.clear();
}else{
value--;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Delete Button OnClickListener");
e.printStackTrace();
}
});
}
private void updateAdapter(){
try {
smallCardAdapter.setItems(myItems);
}catch (Exception e){
Log.w("MainActivity","updateAdapter");
e.printStackTrace();
}
}
The custom Item called MyItem:
public class MyItem {
String firstString;
String secondString;
public MyItem(String firstString,String secondString){
this.firstString = firstString;
this.secondString = secondString;
}
public String getFirstString() {
return firstString;
}
public void setFirstString(String firstString) {
this.firstString = firstString;
}
public String getSecondString() {
return secondString;
}
public void setSecondString(String secondString) {
this.secondString = secondString;
}
}
The Adapter.java creates a smallCard:
public class Adapter extends RecyclerView.Adapter<Adapter.SmallCardHolder> {
private List<MyItem> items = new ArrayList<>();
#NonNull
#Override
public SmallCardHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// I created a new smallcard for the CardView
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.smallcard, parent, false);
SmallCardHolder smallCardHolder = new SmallCardHolder(itemView);
return smallCardHolder;
}
#Override
public void onBindViewHolder(#NonNull final SmallCardHolder holder, int position) {
//get the current item of the position
MyItem myItem = items.get(position);
String firstString = myItem.getFirstString();
String secondString = myItem.getSecondString();
holder.textViewSet.setText(firstString);
holder.textViewkg.setText(secondString);
}
#Override
public int getItemCount () {
return items.size();
}
public void setItems(List <MyItem> items) {
this.items = items;
notifyDataSetChanged();
}
class SmallCardHolder extends RecyclerView.ViewHolder {
//Here are the TextView's of the smallcard (smallcard.xml)
private TextView textViewSet;
private TextView textViewkg;
public SmallCardHolder(#NonNull View itemView) {
super(itemView);
textViewSet = itemView.findViewById(R.id.set);
textViewkg = itemView.findViewById(R.id.kg);
}
}
}
Create a new layout with name called smallcard.xml for the Adapter.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:layout_centerVertical="true"
android:textSize="18sp"
android:layout_marginStart="5dp"
android:textColor="?attr/colorPrimary"
android:textStyle="bold"/>
<TextView
android:id="#+id/kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:layout_toRightOf="#id/set"
android:layout_marginLeft="55dp"
android:layout_centerVertical="true"
android:textColor="?attr/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="10dp"
android:maxLines="1"/>
</RelativeLayout>
</RelativeLayout>
In your XML you have to give the CardView a name. I called it cardView. Here is the code android:id="#+id/cardView"
Result:
You will find more information as comments in the code.
Is it possible to create something like a NumberPicker Widget in android but populate it with a series of strings pulled from an SQLite database?
If there's only one entry, then the spinner would have one string, if there is a hundred, then there would be a hundred entries. There cannot be less than one entry by design, as in, the activity can't be entered without at least one entry. There is no hardset upper limit, but the data will be populated by date and it is VERY unlikely that this data set would ever exceed a thousand entries due to the nature of how the data is created.
What I'm trying to do is show data saved in an SQLite database, the name of each dataset would be displayed in the NumberPicker, then the user could quickly scroll through the data. The data is then going to be be displayed in a Bar Chart (MPandroidcharts library), as they scroll past the dataset in the NumberPicker. At least, that's the goal.
I've managed the SQLite database, and I've got the charts working for single datasets, I just can't figure out how to get the data selection side working.
Try this code this is just a List Activity that is backed by a Recycler Adapter the XML for the List Activity is included and the Card Layout XML file
public class ListActivity extends AppCompatActivity {
DBHelper helper;
static List<DBModel>dbList;
RecyclerView mRecyclerView;
private static RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
addListenerOnButtonAdd();
TextView tvNoData = (TextView)findViewById(R.id.tvNoData);
setTitle("");// This sets the title of the toolbar
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
//topToolBar.setLogo(R.drawable.keyss);// See Notes in MainActivity
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
helper = new DBHelper(this);
dbList = new ArrayList<>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// Code below defines the adapter
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
int sz = dbList.size();
if(sz == 0){
tvNoData.setVisibility(View.VISIBLE);
tvNoData.setText("No Data");
}
}
// This method is called from DetailsActivity and notifies Recycler View
that the DB was changed
of DB and Recycler View
public static void removeListRow(int position) {
dbList.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, dbList.size());
}
/* this BUTTON is on the ToolBar click to ADD new record */
private void addListenerOnButtonAdd() {
// Navigate to DetailsActivity to ADD new DATA
Toolbar tb = (Toolbar) findViewById( R.id.toolbar );
setSupportActionBar( tb );
tb.findViewById( R.id.btnAdd ).setOnClickListener( new
View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSP = new Intent(ListActivity.this,
DetailsActivity.class );
Bundle extras = new Bundle();
extras.putString("FROM_LIST_ACTIVITY","true" );
intentSP.putExtras(extras);
startActivity( intentSP );
}
} );
}
public void onBackPressed(){
Intent intent = new Intent( ListActivity.this, MainActivity.class );
startActivity( intent );
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/color_lightGray"
android:orientation="vertical"
tools:context="com.searchdb.ListActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#color/color_darkGray"
android:layout_width="match_parent"
android:layout_height="64dp">
<ImageView
android:id="#+id/imageTB"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="4dp"
android:src="#drawable/keyss" />
<TextView
android:text="#string/list_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/toolbar"
android:layout_alignParentStart="true"
android:layout_marginStart="30dp"
android:layout_marginBottom="20dp"
android:id="#+id/tvLA"
android:textStyle="bold"
android:textColor="#color/color_White"
android:textSize="22sp" />
<Button
android:text="#string/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnAdd"
android:layout_marginLeft="100dp"
android:textSize="18sp"
android:textStyle="bold"
android:focusable="false"
android:textColor="#color/color_White"
android:background="#color/color_Transparent"/>
</android.support.v7.widget.Toolbar>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvNoData"
android:gravity="center"
android:layout_marginTop="240dp"
android:visibility="invisible"
android:textAllCaps="true"
android:textStyle="bold"
android:textSize="30sp"
android:textColor="#color/color_Red" />
</LinearLayout>
</LinearLayout>
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DBModel> dbList;
static private Context context;
int sz;
RecyclerAdapter(Context context, List<DBModel> dbList) {
RecyclerAdapter.dbList = new ArrayList<>();
RecyclerAdapter.context = context;
RecyclerAdapter.dbList = dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
View itemLayoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int
position) {
holder.rowid.setText(String.valueOf(dbList.get(position).getRowid()));
holder.station.setText(dbList.get(position).getStation_Name());
System.out.println("RecyclerAdapter BindViewHolder FIRST position
"+position);
}
#Override
public int getItemCount() {
return dbList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public TextView station, rowid;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
station = (TextView) itemLayoutView.findViewById(R.id.rvSTATION);
// Attach a click listener to the entire row view
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intentN = new Intent(context, DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("POSITION", getAdapterPosition());
extras.putString("FROM_LIST_ACTIVITY", "false");
intentN.putExtras(extras);
context.startActivity(intentN);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/color_White">
<TextView
android:id="#+id/rvROWID"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="left|center_vertical"
android:padding="10dp"
android:textAlignment="center"
android:text="Position ID"
android:textColor="#color/color_Black"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:textSize="16sp"/>
<TextView
android:id="#+id/rvSTATION"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:padding="10dp"
android:gravity="right|center_vertical"
android:text="Station"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#color/color_Black" />
</RelativeLayout>
</android.support.v7.widget.CardView>
I have used a FirebaseRecyclerAdapter in my application for displaying a series of events. When i select an event form the recycler view it must expand the recycler view item and show me the details and other items of that event such as dates, description and others. I used a concept from Google I/O 2016 but could't land anywhere as my event is not showing only. I want only a specific set of items to be displayed when expanded.
EventView.java
public class EventView extends AppCompatActivity {
DatabaseReference databaseReference;
RecyclerView recyclerView;
int mExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_view);
databaseReference = FirebaseDatabase.getInstance().getReference().child("ApprovedEvents");
recyclerView = (RecyclerView) findViewById(R.id.request_EventList);
//Avoid unnecessary layout passes by setting setHasFixedSize to true
recyclerView.setHasFixedSize(true);
//Select the type of layout manager you would use for your recyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
final String event_cat = getIntent().getStringExtra("Category");
FirebaseRecyclerAdapter<Event, RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, RequestViewHolder>(
Event.class,
R.layout.events_list_row,
RequestViewHolder.class,
databaseReference.orderByChild("category").equalTo(event_cat)
) {
#Override
protected void populateViewHolder(RequestViewHolder viewHolder, Event model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setCategory(model.getCategory());
viewHolder.setLocation(model.getLocation());
viewHolder.setPrice(model.getPrice());
viewHolder.setImageUrl(getApplicationContext(), model.getImageUrl());
viewHolder.imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(EventView.this, "Image Selected", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onBindViewHolder(RequestViewHolder viewHolder, final int position) {
super.onBindViewHolder(viewHolder, position);
final boolean isExpanded = position == mExpandedPosition;
viewHolder.mView.setVisibility(isExpanded?View.VISIBLE:View.GONE);
viewHolder.mView.setActivated(isExpanded);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
TransitionManager.beginDelayedTransition(recyclerView);
notifyDataSetChanged();
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView imageButton;
public RequestViewHolder(View itemView) {
super(itemView);
mView = itemView;
imageButton = (ImageView) mView.findViewById(R.id.request_image);
}
public void setTitle(String title) {
TextView a_title = (TextView) mView.findViewById(R.id.request_title);
a_title.setText(title);
}
public void setDesc(String desc) {
TextView a_desc = (TextView) mView.findViewById(R.id.request_desc);
a_desc.setText(desc);
}
public void setLocation(String location) {
TextView a_desc = (TextView) mView.findViewById(R.id.request_location);
a_desc.setText(location);
}
public void setCategory(String category) {
TextView a_category = (TextView) mView.findViewById(R.id.request_category);
a_category.setText(category);
}
public void setPrice(String price) {
TextView a_price = (TextView) mView.findViewById(R.id.request_price);
a_price.setText(price);
}
public void setImageUrl(Context ctx, String imageUrl) {
ImageView a_image = (ImageView) mView.findViewById(R.id.request_image);
Picasso.with(ctx).load(imageUrl).into(a_image);
}
}
}
events_list_row.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:weightSum="1"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/request_category"
android:textStyle="bold"
android:textSize="15dp"
android:padding="5dp"
android:layout_gravity="left"
android:text="Category will come here"/>
<TextView
android:layout_width="191dp"
android:layout_height="wrap_content"
android:id="#+id/request_location"
android:textSize="15dp"
android:gravity="right"
android:layout_gravity="right"
android:text="Location will come here"
android:padding="5dp"
android:textStyle="bold"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/request_title"
android:layout_marginTop="300dp"
android:text="Title will come here "
android:padding="10dp"
android:textStyle="bold"
android:textSize="15dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/request_desc"
android:text="Desc will come here "
android:layout_marginTop="250dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<ImageView
android:layout_width="match_parent"
android:layout_height="275dp"
android:id="#+id/request_image"
android:src="#drawable/abc_btn_check_material"
android:adjustViewBounds="true"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Price will come here"
android:id="#+id/request_price"
android:layout_marginTop="270dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"/>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_event_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.admin.college20.EventView">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/request_EventList"
android:clickable="true"/>
</RelativeLayout>
my item_layout xml (see it like a template) contain a cardview with some texts and one button, when I run the application. the recyclerview shows two card views with different text (actor names, actors movies) all its ok, but the problem is when I made the button with an onclicklister method to show other activities. the result is when I click on button of the first card view and the button of the second cardview it shows the same result.
what I want is when I click on button on the first cardview it shows Activity number 2, and when I click on the button on the second cardview must shows Activity number 3.
ps: I want different result when I click on button of each cardview
xml :
<RelativeLayout
android:longClickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="7dp">
<ImageView
android:id="#+id/profileImage"
android:layout_width="70dp"
android:layout_height="50dp"
app:civ_border_color="#7f89e9"
android:layout_marginLeft="5dp"
android:background="#drawable/contact1"
android:layout_alignTop="#+id/txtCelebName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginTop="8dp"
android:id="#+id/txtCelebName"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/profileImage"
android:text="Large Text"
android:layout_marginLeft="18dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_marginLeft="18dp"
android:textSize="13dp"
android:id="#+id/txtCelebMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtCelebName"
android:layout_toRightOf="#+id/profileImage"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/textView"
android:layout_marginLeft="10dp"
android:layout_marginTop="27dp"
android:layout_below="#+id/profileImage"
android:text="heur/travaille : 5:00 pm - 8:00 am." />
<TextView
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="emplacement de travaille : cité12 - cité42. "
android:id="#+id/textView2"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="statut : disponible."
android:id="#+id/textView3"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="#+id/textView4"
android:layout_below="#+id/profileImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="...................................."
android:id="#+id/textView5"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4"
android:layout_below="#+id/textView2"
android:layout_marginBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="go"
android:id="#+id/buttonfordialog"
android:layout_alignBottom="#+id/textView4"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3" />
</RelativeLayout>
MainActivity java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ItemAdapter itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
};
final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
collapsingToolbarLayout.setTitle("Alert ! ");
ArrayList<Celebrity> itemList = new ArrayList<>();
fillDummyData(itemList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
itemAdapter = new ItemAdapter(itemList, btnListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemAdapter);
}
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ##._V1._SY209_CR13,0,140,209_.jpg");
celebList.add(celeb2);
}
}
the Adapter :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;
public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
this.celebrityList = celebrityList;
this.btnListener = btnListener;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new ItemHolder(itemView, btnListener);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
}
#Override
public int getItemCount() {
return celebrityList.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
private Button buttoncalling;
public TextView txtCelebName, txtCelebMovie;
public ImageView profileImage;
public ItemHolder(View view, View.OnClickListener btnListener) {
super(view);
txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
profileImage = (ImageView) view.findViewById(R.id.profileImage);
buttoncalling = (Button) view.findViewById(R.id.buttonfordialog);
buttoncalling.setOnClickListener(btnListener);
}
}
}
define OnClickListener inside onBindViewHolder();
String [] activities={"FirstActivity","SecondActivity","ThirdActivity"};
String packageNamePrefix="com.example."
//String packageNamePrefix="YOUR_PACKAGE_NAME"
#Override
public void onBindViewHolder(ItemHolder holder,final int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
holder.buttoncalling.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new
Intent(MainActivity.this,Class.forName(packageNamePrefix+activities[position]));
startActivity(intent);
}
});
}
it will launch FirstActivity,SecondActivity,ThirdActivity respectively.
I hope it will help.
There are many ways to implement OnClickListener inside RecyclerView adapter.
You can implement click listener inside onBindViewHolder() method like below
holder.buttoncalling.setOnClickListener(new View.OnClickListener(){
// perform click operation
});
You can also implement it inside you ItemHolder like this
buttoncalling.setOnClickListener( new View.OnClickListener(){
// perform click operation
});
and use getAdapterPosition() whenever you need item clicked position as recommended in official docs.
You can also make interface callbacks to your Activity and pass position along with it for refrence.
You should use inline onclickListener like below;
YOURBUTTON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your codes goes here...
}
});
Friends i'm new to android and learning on my own. I was creating invoice manager app for learning. Here products are added by the admin and that is working fine. User has only permission to create invoice. When user arrives into create_invoice activity he has set of frame layouts in which one is for adding items. When user presses the frame layout he is made to see another activity where he can find all set of list items along with the product price in List view which admin has added. Now when user presses an item he is again brought back to create_invoice activity and a alert box appears which asks the qty required. When user enters the qty and clicks OK button, for the first the list item is displayed properly as i require. But when i add second item, 1st item gets replaced. So now my problem is how can i resolve this problem.. Guys please help me. Codes you people find may be very silly but i'm still learning. Thanks in advance.
Create_invoice activity
//data from activity invoice add_item
product_name = intent.getStringExtra("product_name");
product_price = intent.getDoubleExtra("product_price",0);
//product_qty = intent.getIntExtra("product_qty",0);
product_code = intent.getIntExtra("product_code",0);
if(product_name!= null && product_price!= 0 && product_code!= 0)
{
try {
builder = new AlertDialog.Builder(this);
builder.setTitle("Product Qty");
layoutInflater = LayoutInflater.from(Create_invoice.this);
view = layoutInflater.inflate(R.layout.dialoglayout_invoice,null);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
EditText etxt_dialog_qty=(EditText)view.findViewById(R.id.
etxt_dialog_qty);
int qty = Integer. parseInt (etxt_dialog_qty.getText().
toString().trim());
invoice_product_list products = new invoice_product_list
(product_name, product_price, qty, product_code);
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.add(products);
customAdapterInvoice.notifyDataSetChanged();
//listview in create_invoice activity
listView_additem = (ListView)
findViewById(R.id.listview_additem);
listView_additem.setAdapter(customAdapterInvoice);
alertDialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
catch (Exception e)
{
System.out.print(e);
}
}
customAdapter
public class custom_adapter_invoice extends ArrayAdapter
<invoice_product_list> {
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view =
layoutInflater.inflate(R.layout.custom_row_invoice_item,parent,false);
invoice_product_list products = getItem(position);
TextView txt_product_name =
(TextView)view.findViewById(R.id.txt_product_name);
TextView txt_product_price =
(TextView)view.findViewById(R.id.txt_product_price);
TextView txt_product_qty =
(TextView)view.findViewById(R.id.txt_product_qty);
TextView txt_product_code =
(TextView)view.findViewById(R.id.txt_product_code);
txt_product_name.setText(products.getProduct_name());
txt_product_price.setText(String.valueOf(products.getProduct_price()));
txt_product_qty.setText(String.valueOf(products.getProduct_qty()));
txt_product_code.setText(String.valueOf(products.getProduct_code()));
return view;
}
create invoice activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tournonstop.m.invoicemanager.Create_invoice"
tools:showIn="#layout/activity_create_invoice">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_company">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/company_name"
android:id="#+id/txt_company_name"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_date"
android:id="#+id/txt_invoice_date"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_no"
android:id="#+id/textView3"
android:layout_marginLeft="15dp"
android:layout_marginTop="45dp"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_client"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/to"
android:id="#+id/txt_to"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_client_address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:hint="#string/client_hint"/>
</FrameLayout>
----listview to add items-----
<FrameLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_add_item"
android:clickable="true">
<ListView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/listview_additem"
android:divider="#040404" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_sub_total">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total_label"
android:id="#+id/txt_sub_total_label"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total"
android:id="#+id/txt_sub_total"
android:layout_gravity="right"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textStyle="bold"
android:hint="#string/total_hint" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/invoice_btn"
android:textStyle="bold"
android:background="#color/colorPrimaryDark"
android:textColor="#android:color/white"
android:clickable="true"
android:id="#+id/btn_invoice_save" />
</LinearLayout>
< /android.support.v4.widget.DrawerLayout>
invoice product list(getters and setters)
package com.tournonstop.m.invoicemanager;
public class invoice_product_list {
private String product_name;
private double product_price;
private int product_qty;
private int product_code;
public invoice_product_list(){
}
public invoice_product_list(String product_name,double
product_price,int product_qty,int product_code){
this.product_name = product_name;
this.product_price = product_price;
this.product_qty = product_qty;
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public double getProduct_price() {
return product_price;
}
public void setProduct_price(double product_price) {
this.product_price = product_price;
}
public int getProduct_qty() {
return product_qty;
}
public void setProduct_qty(int product_qty) {
this.product_qty = product_qty;
}
}
Add item to your list that you're using in adapter and (after verifying adapter is not null ) call method notifyDataSetChanged () on adapter object.
create_invoice activity
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.addProduct(products)
custom Adapter
public class custom_adapter_invoice extends ArrayAdapter <invoice_product_list>
{
ArrayList<invoice_product_list> productList = new ArrayList<>();
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
this.productList =product_details
}
public void addProduct(Product products
productList.add(products);
notifyDataSetChanged();
}
......
}
No,it does not change anything. If you want the latest method of working then I would prefer RecyclerView to custom list adapter. this link is very good for recyclerview
recyclerview demo series link