Items in the RecyclerView are not showing - android

List_items are not showing in the RecyclerView.
Have tried changing the layout height and other answers.
The list_items should contain
-item_name
-item_quantity
-date
So basically after entering the respective dataset in an AlertDialog and after clicking the save button, the ListActivity will show up. But a Blank Screen is showing up not containing the list_items within the CardView.
Here's the ListActivity
package com.example.akash.distributedapp.DatabaseApp.Activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.akash.distributedapp.DatabaseApp.Data.DatabaseHandler;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.DatabaseApp.UI.RecyclerViewAdapter;
import com.example.akash.distributedapp.R;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private DatabaseHandler db;
private RecyclerView recyclerView;
private List<Grocery> groceryList;
private List<Grocery> listItems;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
db = new DatabaseHandler(this);
recyclerView = findViewById(R.id.recyclerViewID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
groceryList = new ArrayList<>();
listItems = new ArrayList<>();
//get items from database
groceryList = db.getAllGroceries();
for(Grocery c : groceryList){
Grocery grocery = new Grocery();
grocery.setName(c.getName());
grocery.setQuantity("Qty:" + c.getQuantity());
grocery.setId(c.getId());
grocery.setDateItemAdded("Added on: " + c.getDateItemAdded());
listItems.add(grocery);
}
recyclerViewAdapter = new RecyclerViewAdapter(this, listItems);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
}
Here's the adapter class
package com.example.akash.distributedapp.DatabaseApp.UI;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private Context context;
private List<Grocery> groceryItems;
public RecyclerViewAdapter(Context context, List<Grocery> groceryItems) {
this.context = context;
this.groceryItems = groceryItems;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Grocery grocery = groceryItems.get(position);
holder.groceryItemName.setText(grocery.getName());
holder.quantity.setText(grocery.getQuantity());
holder.quantity.setText(grocery.getDateItemAdded());
}
#Override
public int getItemCount() {
return groceryItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView groceryItemName;
public TextView quantity;
public TextView dateAdded;
public Button editBtn;
public Button deleteBtn;
public int id;
public ViewHolder(View itemView, Context ctx) {
super(itemView);
context = ctx;
groceryItemName = itemView.findViewById(R.id.tv_item);
quantity = itemView.findViewById(R.id.tv_qty);
dateAdded = itemView.findViewById(R.id.tv_date);
editBtn = itemView.findViewById(R.id.btn_edit);
deleteBtn = itemView.findViewById(R.id.btn_delete);
editBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opens new activity
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_edit:
break;
case R.id.btn_delete:
break;
}
}
}
}
Here is my XML file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="125dp"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:padding="15dp"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_item"
android:text="Grocery name"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_qty"
android:layout_below="#+id/tv_item"
android:text="Quantity"
android:paddingTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_date"
android:paddingTop="5dp"
android:text="Date"
android:layout_below="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableRow
android:layout_alignParentRight="true"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/btn_edit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="15dp"
android:background="#android:drawable/ic_menu_edit"/>
<Button
android:id="#+id/btn_delete"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#android:drawable/ic_delete"/>
</TableRow>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

Related

Recycler View leaving huge space before printing next card view

I'm trying to show all the card views using recycler view in main activity. Although I did not set a huge margin between card views, my recycler view shows a huge space to print the next card view. please see my attached image, you'll understand what I'm trying to say. I've attached all the code here. Can you please advise how to solve this problem? Thank you.
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/note_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/add" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="7dp"
app:cardBackgroundColor="#color/green"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitleCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="TextView"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewDescriptionCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.destructivepaul.quicknote;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteHolder>{
private List<MyNote> myNoteList = new ArrayList<>();
// private Context context;
public void setMyNoteList(List<MyNote> myNoteList) {
this.myNoteList = myNoteList;
notifyDataSetChanged();
Log.i("info","note updated on adapter. note list size: "+myNoteList.size());
}
//public void setContext(Context context) {
// this.context = context;
// notifyDataSetChanged();
// Log.i("info","context updated on adapter");
// }
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.note_card
,parent,false);
return new NoteHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteHolder holder, int position) {
MyNote myNote=myNoteList.get(position);
holder.textViewTitle.setText(myNote.getNote_title());
holder.textViewDescription.setText(myNote.getNote_description());
}
#Override
public int getItemCount() {
return myNoteList.size();
}
public class NoteHolder extends RecyclerView.ViewHolder{
private TextView textViewTitle, textViewDescription;
private CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
textViewTitle=itemView.findViewById(R.id.textViewTitleCard);
textViewDescription=itemView.findViewById(R.id.textViewDescriptionCard);
cardView=itemView.findViewById(R.id.cardView);
Log.i("info","card design found on adapter");
}
}
}
package com.destructivepaul.quicknote;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fab;
private RecyclerView recyclerView;
private MyNoteViewModel myNoteViewModel;
private ActivityResultLauncher<Intent> activityResultLauncherForAddNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//resisterActivity
resisterActivityForAddNote();
fab=findViewById(R.id.fab);
recyclerView=findViewById(R.id.recyclerView);
NoteAdapter adapter=new NoteAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
Log.i("info","set the adapter");
myNoteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
.create(MyNoteViewModel.class);
myNoteViewModel.getAllNotes().observe(MainActivity.this, new Observer<List<MyNote>>() {
#Override
public void onChanged(List<MyNote> myNotes) {
adapter.setMyNoteList(myNotes);
Log.i("info","adapter is called to update data");
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(MainActivity.this,CreateNoteActivity.class);
//resister activity launcher
activityResultLauncherForAddNote.launch(intent);
Log.i("info","called resister activity launcher on fab");
}
});
}
public void resisterActivityForAddNote(){
activityResultLauncherForAddNote=registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
int resultCode=result.getResultCode();
Intent data = result.getData();
if (resultCode==RESULT_OK && data !=null) {
String title = data.getStringExtra("title");
String description = data.getStringExtra("description");
String colorName = data.getStringExtra("color");
MyNote myNote = new MyNote(title, description, colorName);
Log.i("info", "new note created on activity result");
myNoteViewModel.insert(myNote);
Log.i("info", "note saved to database");
}
}
});
}
}
I've solved my problem by myself. The problem was on card layout design(parent layout height should be wrap content instead of match parent).

How to remove the last item in recyclerview adapter by a button?

I have a recyclerview and I want to delete the last item on it when I click a button that is not in the recyclerview. I want to delete the item and notify the adapter that the item is deleted so I can enter another item. By the way, the items I enter are by edittext and a button.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.brecyclerview.MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/edit_ten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Score"
android:inputType="numberSigned|number" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_add"
android:text="Add"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_undo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_undo"
android:text="Undo"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_new"
android:text="New Game" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:itemCount="8" />
</LinearLayout>
list_item.xml:
<?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="wrap_content">
<RelativeLayout
android:id="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/userImg"
android:src="#mipmap/ic_launcher"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:id="#+id/pNametxt"
android:text="User Name"
android:textSize="20sp"
android:layout_marginTop="6dp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/userImg"
android:layout_toEndOf="#+id/userImg"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" />
</RelativeLayout>
<View
android:layout_below="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f2f2f2" />
</RelativeLayout>
MainActivity.java:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
int total = 0;
Button button;
Button button1;
Button button2;
EditText editText;
TextView personName;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
List<PersonUtils> personUtilsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.btn_add);
button1 = (Button)findViewById(R.id.btn_undo);
button2 = (Button)findViewById(R.id.btn_new);
editText = (EditText)findViewById(R.id.edit_ten);
personName = (TextView)findViewById(R.id.pNametxt);
recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList = new ArrayList<>();
mAdapter = new CustomRecyclerAdapter(this, personUtilsList);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == button2) {
MainActivity.this.finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}}});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
total = personUtilsList.get(i).getPersonName();
}
total += Integer.parseInt(editText.getText().toString());
personUtilsList.add(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
editText.setText("");
}});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
personUtilsList.remove(i).getPersonName();
personUtilsList.remove(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}}
});
}}
CustomRecyclerAdapter.java:
import android.content.Context;
import android.preference.PreferenceScreen;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {
private Context context;
private List<PersonUtils> personUtils;
public CustomRecyclerAdapter(Context context, List personUtils) {
this.context = context;
this.personUtils = personUtils;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setTag(personUtils.get(position));
PersonUtils pu = personUtils.get(position);
holder.pName.setText(String.valueOf(pu.getPersonName()));
}
#Override
public int getItemCount() {
return (personUtils.size()>8)?8:personUtils.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView pName;
final Button deleteButton;
public ViewHolder(final View itemView) {
super(itemView);
pName = (TextView) itemView.findViewById(R.id.pNametxt);
deleteButton = (Button) itemView.findViewById(R.id.btn_undo);
}
}}
PersonUtils.java:
public class PersonUtils {
private Integer personName;
public static void remove(int index) {
}
public Integer getPersonName() {
return personName;
}
public void setPersonName(Integer personName) {
this.personName = personName;
}
public PersonUtils(Integer personName) {
this.personName = personName;
}
}
I expect to delete the last item (integer) in the recyclerview and notify the adapter so I can edit the value when needed.
You can add a method in your adapter to remove last item in the list:
public ViewHolder removeLastItem() {
if (personUtils == null || personUtils.isEmpty()) return;
personUtils.removeAt(personUtils.getSize()-1);
notifyDataSetChanged();
}
When the button is clicked, just call:
adapter.removeLastItem()
Check if you are in the last index, then remove the item and use notifyItemRemoved to notify any registered observers:
if(currentPosition == 0){
listOfItems.removeAt(currentPosition)
notifyItemRemoved(currentPosition)
}

how to make a dialog pop up after the list view reach a specific integer?

i have a recyclerview with a textview inside it that accept integers only from an edittext and a button that outside the recyclerview and everytime i add an integer to the recyclerview it gets added to the one before that.
so i want a set a dialog after it reach a 2000 or higher and the dialog should be asking if i want to recreate the activity or move to another activity.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.brecyclerview.MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/edit_ten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Score"
android:inputType="numberSigned|number" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_add"
android:text="Add"
android:enabled="false"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_undo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_undo"
android:text="Undo"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_new"
android:text="New Game" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:itemCount="8" />
</LinearLayout>
list_item.xml
<?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="wrap_content">
<RelativeLayout
android:id="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/userImg"
android:src="#mipmap/ic_launcher"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:id="#+id/pNametxt"
android:text="User Name"
android:textSize="20sp"
android:layout_marginTop="6dp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/userImg"
android:layout_toEndOf="#+id/userImg"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" />
</RelativeLayout>
<View
android:layout_below="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f2f2f2" />
</RelativeLayout>
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
int total = 0;
Button button;
Button button1;
Button button2;
EditText editText;
TextView personName;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
List<PersonUtils> personUtilsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn_add);
button1 = (Button) findViewById(R.id.btn_undo);
button2 = (Button) findViewById(R.id.btn_new);
editText = (EditText) findViewById(R.id.edit_ten);
personName = (TextView) findViewById(R.id.pNametxt);
recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList = new ArrayList<>();
mAdapter = new CustomRecyclerAdapter(this, personUtilsList);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String addvalue = editText.getText().toString().trim();
button.setEnabled(!addvalue.isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == button2) {
recreate();
}}});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < personUtilsList.size(); i++) {
total = personUtilsList.get(i).getPersonName();
}
total += Integer.parseInt(editText.getText().toString());
personUtilsList.add(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
editText.setText("");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = mAdapter.getItemCount() -1;
removeItem(position);
}
});
}
public void removeItem(int position) {
if(position <= 0)
{ recreate();
}
else if(position == mAdapter.getItemCount() - 1)
{personUtilsList.remove(position);
mAdapter.notifyItemRemoved(position);
}
else
{
}
}
});}}
CustomRecyclerAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {
private Context context;
private static List<PersonUtils> personUtils;
public CustomRecyclerAdapter(Context context, List personUtils) {
this.context = context;
this.personUtils = personUtils;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setTag(personUtils.get(position));
PersonUtils pu = personUtils.get(position);
holder.pName.setText(String.valueOf(pu.getPersonName()));
}
#Override
public int getItemCount() {
return (personUtils.size()>8)?8:personUtils.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView pName;
final Button deleteButton;
public ViewHolder(final View itemView) {
super(itemView);
pName = (TextView) itemView.findViewById(R.id.pNametxt);
deleteButton = (Button) itemView.findViewById(R.id.btn_undo);
}}}
PersonUtils.java
public class PersonUtils {
private Integer personName;
public Integer getPersonName() {
return personName;
}
public void setPersonName(Integer personName) {
this.personName = personName;
}
public PersonUtils(Integer personName) {
this.personName = personName;
}
}
i want a set a dialog after it reach a 2000 or higher and the dialog should be asking if i want to recreate the activity or move to another activity.
In your RecyclerView add ScrollListener to listen scroll event. Please check below:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int position = ((LinearLayoutManager)recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if(position == 2000) {
//ToDo: Whatever you want to do
}
}
}
});

Expandable layout Expands upwards instead of downwards

When i try to put my Expandable layout to the bottom of my cardview using
android:layout_gravity="bottom" it goes to the bottom but expands upwards
After clicking the relative layout "button"
I am getting data from arraylist passing it to the recyclerview and cardview
i don't know if it's because of the Adapter animation settings or just fomr the xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_gravity="top"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="551dp"
android:animateLayoutChanges="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/holderimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView5"
android:layout_width="68dp"
android:layout_height="62dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/s1960678" />
<TextView
android:id="#+id/nameArray"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:fontFamily="serif"
android:includeFontPadding="false"
android:text="TextView"
android:textSize="14sp"
android:textStyle="bold" />
<RelativeLayout
android:id="#+id/button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_arrow_drop_down_black_24dp"
android:foregroundGravity="right"
android:gravity="right|center_horizontal"
android:orientation="vertical">
<View
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<com.github.aakira.expandablelayout.ExpandableLinearLayout
android:id="#+id/expandableLayout"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:foregroundGravity="bottom"
android:gravity="top"
android:orientation="vertical"
app:ael_duration="400"
app:ael_expanded="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button3"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:text="Button"
tools:text="Download .PDF" />
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
tools:text="View PDF" />
</LinearLayout>
</com.github.aakira.expandablelayout.ExpandableLinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
and here's the activity it gets data from , it's xml has only recyclerview
package com.example.imc.PDF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.imc.MainAdapter;
import com.example.imc.MySingleton;
import com.example.imc.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Resultsdwldview extends AppCompatActivity {
public RequestQueue requestQueue;
TextView MedicalText,PhoneText,AddressText,EmailText,result,resultArray;
EditText id;
Button getidbtn;
List<ArrayList<String>> Tests = new ArrayList<>();
ArrayList<String> urlArray = new ArrayList<String>();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<String> IdfromjsonArray = new ArrayList<String>();
ArrayList<String> Patient_ID_Array = new ArrayList<String>();
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
WebView webView;
String PDFurl;
String idvalue;
String url = "https://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resultsdwldview);
MedicalText = findViewById(R.id.MedicalText);
PhoneText = findViewById(R.id.PhoneText);
AddressText = findViewById(R.id.AddressText);
EmailText = findViewById(R.id.EmailText);
// webView = findViewById(R.id.webview); //WEBVIEW
// webView.requestFocus();
// webView.getSettings().setJavaScriptEnabled(true);
// webView.loadUrl(url);
mRecyclerView = findViewById(R.id.recyvlerView);
// id = findViewById(R.id.getid);
// getidbtn =(Button) findViewById(R.id.send);
mLayoutManager = new LinearLayoutManager(this);
jsonParse();
/*
getidbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//idvalue = id.getEditableText().toString();
jsonParse();
}
});*/
}
public void jsonParse() {
String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+4;
//String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+idvalue;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Tests");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arraydata = jsonArray.getJSONObject(i);
// Tests.add(jsonObject.getString(String.valueOf(i)));
String urlName = arraydata.getString("urlName");
String Name =arraydata.getString("Name");
String Idfromjson =arraydata.getString("Id");
String P_ID_Array =arraydata.getString("patients_Id");
urlArray.add(urlName);
nameArray.add(Name);
IdfromjsonArray.add(Idfromjson);
Patient_ID_Array.add(P_ID_Array);
Tests.add(urlArray);
Tests.add(nameArray);
Tests.add(IdfromjsonArray);
Tests.add(Patient_ID_Array);
// resultArray.append("urlName = " +urlName+" \n\n Name"+Name);
}
//resultArray.append(Tests+" , \n ");
// mRecyclerView.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Integer P_MedicalNumber = response.getInt("MedicalNumber");
Integer P_id = response.getInt("Id");
String P_Username = response.getString("UserName");
Integer P_PhoneNumber = response.getInt("phoneNumber");
String P_Address = response.getString("Address");
String P_Email = response.getString("Email");
//result.append("Medical Number : "+P_MedicalNumber+" \n id :"+P_id+"UserName"+P_Username);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new MainAdapter(Tests,nameArray);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemRangeInserted(0, Tests.size());
// webView.loadUrl(PDFurl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
// requestQueue.add(request);
MySingleton.getInstance(Resultsdwldview.this).addToReqeustQueue(jsonObjectRequest);
}
}
Adapter
package com.example.imc;
import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.aakira.expandablelayout.ExpandableLayout;
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableLinearLayout;
import com.github.aakira.expandablelayout.Utils;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
List<ArrayList<String>> Tests;
ArrayList<String> urlArray;
ArrayList<String> nameArray;
ArrayList<String> IdfromjsonArray ;
ArrayList<String> Patient_ID_Array;
SparseBooleanArray expandState =new SparseBooleanArray();
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> urlArray, ArrayList<String> nameArray,
ArrayList<String> idfromjsonArray, ArrayList<String> patient_ID_Array) {
Tests = tests;
this.urlArray = urlArray;
this.nameArray = nameArray;
IdfromjsonArray = idfromjsonArray;
Patient_ID_Array = patient_ID_Array;
}
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> nameArray) {
Tests = tests;
this.nameArray = nameArray;
}
#NonNull
#Override
//Initialize the viewholder
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row,viewGroup,false);
return new ViewHolder(view);
}
/***************////////////////onBind Holds values to pass it to the viewholder///////////////////*******************
/***************////////////////
// This method is called for each ViewHolder to
// bind it to the adapter
// . This is where we will// pass our data to our ViewHolder///////////////////*******************
#Override
public void onBindViewHolder(#NonNull final MainAdapter.ViewHolder holder, final int i) {
// holder.URLName.setText( urlArray.get(i));
holder.mFullname.setText( nameArray.get(i));
holder.expandableLayout.setInRecyclerView(true);
holder.expandableLayout.setExpanded(expandState.get(i));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
changeRotate(holder.button,180f,0f).start();
expandState.put(i,true);
}
#Override
public void onPreClose() {
changeRotate(holder.button,0f,180f).start();
expandState.put(i,false);
}
});
holder.button.setRotation(expandState.get(i)?0f:180f);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Expandable child item
holder.expandableLayout.toggle();
}
});
}
private ObjectAnimator changeRotate(RelativeLayout button, float to, float from) {
ObjectAnimator animator = ObjectAnimator.ofFloat(button,"rotation",from,to);
animator.setDuration(200);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
#Override
public int getItemCount() {
return nameArray.size();
}
/***************////////////////VIEWHOLDER///////////////////*******************
public class ViewHolder extends RecyclerView.ViewHolder {
// public TextView URLName;
public TextView mFullname;
public RelativeLayout button;
public ExpandableLinearLayout expandableLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mFullname=itemView.findViewById(R.id.nameArray);
//URLName=itemView.findViewById(R.id.URLName);
button=itemView.findViewById(R.id.button);
expandableLayout=itemView.findViewById(R.id.expandableLayout);
}
}
}

onItemClick not working for Card View

It uses retrofit 2.0 to fetch the data from the webservice and bind it to the card view. When I click on the card view having image and textviews, on click is not triggering, rather a strange behaviour is at the very corner edges of the card view onclick is triggering.
Item_row.xml
<?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="wrap_content"
android:layout_margin="8dp"
card_view:cardCornerRadius="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:layout_margin="5dp"
android:clickable="true">
<ImageView
android:id="#+id/flowerImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:focusable="true"
android:clickable="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"/>
<ImageButton
android:id="#+id/favIcon"
android:layout_width="32dp"
android:layout_height="32dp"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:background="#drawable/ic_favorite_border"
android:focusable="true"
android:clickable="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/flowerImage"
android:orientation="vertical"
>
<TextView
android:id="#+id/flowerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textColor="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:layout_alignBottom="#id/flowerName"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/flowerCategory"
android:text="New Text"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="New Text"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Content_main.xml
Layout file
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
Main Activity Layout file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:elevation="8dp"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The code base is following MVC design pattern. Controller does the job of getting the web service data
MainActivity.java
package com.innovation.myapp.jwelleryonrent.View;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.controller.jwelleryController;
import com.innovation.myapp.jwelleryonrent.model.adapter.CustomItemClickListner;
import com.innovation.myapp.jwelleryonrent.model.adapter.JwelleryAdapter;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements jwelleryController.JwelleryCallbackListener {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private List<JwelleryCollection> mJwelleryList = new ArrayList<>();
private JwelleryAdapter mJwelleryAdapter;
private jwelleryController mController;
private boolean isInFavourites = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configToolbar();
mController = new jwelleryController(MainActivity.this);
configViews();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.item_row, container, false);
ImageButton imgBtn = (ImageButton) findViewById(R.id.favIcon);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemToBag(v);
}
});
return rootView;
}
private void addItemToBag(View v)
{
isInFavourites = true;
ImageButton btnFaviourite = (ImageButton) findViewById(R.id.favIcon);
if(isInFavourites==true) {
btnFaviourite.setImageResource(R.drawable.ic_favorite_white_24dp);
}
else
btnFaviourite.setImageResource(R.drawable.ic_favorite_border);
Snackbar.make(v, "Item added to Favourites", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
private void configToolbar() {
mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
private void initializeAdapter()
{
mJwelleryAdapter = new JwelleryAdapter(mJwelleryList, new CustomItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Toast.makeText(MainActivity.this, "Clicked Item: "+position,Toast.LENGTH_LONG).show();
}
});
mRecyclerView.setAdapter(mJwelleryAdapter);
mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent),
getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mController.startFetching();
}
});
}
private void configViews() {
mRecyclerView = (RecyclerView) this.findViewById(R.id.list);
mSwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipe);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mController.startFetching();
initializeAdapter();
// mJwelleryAdapter= new JwelleryAdapter(mJwelleryList);
}
#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);
}
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(JwelleryCollection jwellery) {
mJwelleryAdapter.addJwellery(jwellery);
}
#Override
public void onFetchProgress(List<JwelleryCollection> jwelleryList) {
}
#Override
public void onFetchComplete() {
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFetchFailure() {
}
}
Recycler view uses the adapter view holder pattern to initialize the adapter
JwelleryAdapter class
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.View.MainActivity;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import com.innovation.myapp.jwelleryonrent.model.utilities.Constants;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
*
*/
public class JwelleryAdapter extends RecyclerView.Adapter<JwelleryAdapter.Holder> {
private List<JwelleryCollection> mJwelleryCollection;
CustomItemClickListner itemListner;
Context mContext;
public JwelleryAdapter(List<JwelleryCollection> jwellery) {
mJwelleryCollection = jwellery;
}
public JwelleryAdapter( List<JwelleryCollection> jwellery,CustomItemClickListner listner) {
mJwelleryCollection = jwellery;
this.itemListner = listner;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false);
final Holder mViewHolder = new Holder(row);
row.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
itemListner.onItemClick(v,mViewHolder.getPosition());
}
});
return mViewHolder;
}
#Override
public void onBindViewHolder(JwelleryAdapter.Holder holder, int position) {
JwelleryCollection currentJwellery = mJwelleryCollection.get(position);
holder.mName.setText(currentJwellery.mName);
holder.mCategory.setText(currentJwellery.mCategory);
holder.mPrice.setText(Double.toString(currentJwellery.mPrice));
holder.mInstructions.setText(currentJwellery.mInstructions);
Picasso.with(holder.itemView.getContext()).load(Constants.PHOTO_URL + currentJwellery.mPhoto).into(holder.mImage);
}
public void addJwellery(JwelleryCollection jwellery) {
mJwelleryCollection.add(jwellery);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mJwelleryCollection.size();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
Context contxt;
public TextView mName, mCategory, mPrice, mInstructions;
public ImageView mImage;
public Holder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.flowerImage);
mName = (TextView) itemView.findViewById(R.id.flowerName);
mCategory = (TextView) itemView.findViewById(R.id.flowerCategory);
mPrice = (TextView) itemView.findViewById(R.id.flowerPrice);
mInstructions = (TextView) itemView.findViewById(R.id.flowerInstruction);
}
public Holder(View itemView,int ViewType,Context c) {
// Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
contxt = c;
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contxt, "The Item Clicked is: " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
CustomerItemClickListner Interface to handle row item on click
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.view.View;
/**
*
*/
public interface CustomItemClickListner {
public void onItemClick(View v,int position);
}
First create one variable of your interface in your adapter:
CustomItemClickListener mListener;
then like you have set in your OnClick() method:
if (mListener != null) {
mListener.onItemClick(v, getAdapterPosition());
}
and the last thing you need to modify in your adapter is creating new method which you will call later in your activity class for handling listener:
public void setOnItemClickListener(CustomItemClickListener listener) {
mListener = listener;
}
now you can call this method in your activity like this:
adapter.setOnItemClickListener(this); // implement interface
// or
adapter.setOnItemClickListener(new CustomItemClickListener());

Categories

Resources