Custom adapter doesn't change text in listview - java

I'm trying to show the data i got from the firebase in a listview. But my textview in listview doesn't change. This output i have two document my database. Two listview appear but can't change text.Where am i wrong?
OUTPUT
Here's my CustomAdapter code
public class MissionsAdapter extends ArrayAdapter<Missions> {
public MissionsAdapter(Context context, List<Missions> object){
super(context,0, object);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.item_missions,parent,false);
}
Missions mission = getItem(position);
TextView titleTextView = (TextView) convertView.findViewById(R.id.mission_title);
TextView expTextView = (TextView) convertView.findViewById(R.id.mission_exp);
TextView dateTextView = (TextView) convertView.findViewById(R.id.mission_date);
TextView descriptionTextView = (TextView) convertView.findViewById(R.id.mission_description);
TextView bilgitext=(TextView) convertView.findViewById(R.id.mission_bilgi);
titleTextView.setText(mission.getTitle());
expTextView.setText(mission.getExp());
dateTextView.setText(mission.getDate());
descriptionTextView.setText(mission.getDescription());
bilgitext.setText(mission.getBilgi());
return convertView;
}
}
Missions.java
public class Missions {
public String title;
public String exp;
public String date;
public String description;
public String bilgi;
public Missions() {}
public Missions(String title, String exp, String date, String description, String bilgi) {
this.title = title;
this.exp = exp;
this.date = date;
this.description = description;
this.bilgi=bilgi;
}
public String getTitle(){
return title;
}
public String getExp(){
return exp;
}
public String getDate(){
return date;
}
public String getDescription(){
return description;
}
public String getBilgi(){
return bilgi;
}
}
item_missions.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="#+id/mission_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textAppearance="?android:textAppearanceMedium"
android:hint="There will be a title"/>
<TextView
android:id="#+id/mission_exp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be exp"/>
<TextView
android:id="#+id/mission_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a date"/>
<TextView
android:id="#+id/mission_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a description"/>
<TextView
android:id="#+id/mission_bilgi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearance"
android:hint="There will be a bilgi"/>
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/missionHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Edit/Create mission"
android:gravity="center"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textAllCaps="true"
android:textSize="30dp"
android:paddingTop="20dp"
/>
<ListView
android:id="#+id/missionList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
And finally MainActivity
public class MainActivity5 extends AppCompatActivity {
private final String COLLECTION_KEY = "İlanlar";
private TextView mHeaderView;
private ListView mMissionListView;
private FirebaseFirestore db;
private MissionsAdapter mMissionAdapter;
private ArrayList<Missions> mMissionsList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
mHeaderView = (TextView) findViewById(R.id.missionHeader);
mMissionListView = (ListView) findViewById(R.id.missionList);
mHeaderView.setText("Available Missions");
db = FirebaseFirestore.getInstance();
mMissionsList = new ArrayList<Missions>();
mMissionAdapter = new MissionsAdapter(MainActivity5.this, mMissionsList);
mMissionListView.setAdapter(mMissionAdapter);
db.collection(COLLECTION_KEY).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
List<Missions> mMissionsList = new ArrayList<>();
if(task.isSuccessful()){
for(QueryDocumentSnapshot document : task.getResult()) {
Missions miss = document.toObject(Missions.class);
mMissionsList.add(miss);
}
ListView mMissionsListView = (ListView) findViewById(R.id.missionList);
MissionsAdapter mMissionAdapter = new MissionsAdapter(MainActivity5.this, mMissionsList);
mMissionsListView.setAdapter(mMissionAdapter);
} else {
Log.d("MissionActivity", "Error getting documents: ", task.getException());
}
}
});
mMissionAdapter.addAll(mMissionsList);
}
}

Related

How to refer FIrebase Child in Child record in Firebase Recycler adapter to show in recyclerview

I have written code to list contacts in recycler view. But it doesn't display value in recycler view. The code is given below.
HomeActivity.java
private DatabaseReference mDatabase;
private RecyclerView PList;
private FirebaseRecyclerAdapter<project, ProjViewHolder> FBRA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
PList = findViewById(R.id.ProjList);
PList.setHasFixedSize(true);
PList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("Contacts");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>().setQuery(mDatabase, project.class).build();
FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProjViewHolder holder, int position, #NonNull project model) {
String proj_key = getRef(position).getKey();
holder.cpname.setText(model.getCname());
holder.cplocation.setText(model.getCcity());
holder.ccname.setText(model.getPcontact());
holder.ccdesig.setText(model.getPdesig());
}
#Override
public ProjViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
return new ProjViewHolder(view);
}
};
PList.setAdapter(FBRA);
FBRA.startListening();
}
public class ProjViewHolder extends RecyclerView.ViewHolder {
TextView cpname, cplocation, ccname, ccdesig;
ProjViewHolder(#NonNull View itemView) {
super(itemView);
cpname = itemView.findViewById(R.id.FCName);
cplocation = itemView.findViewById(R.id.FCLocation);
ccname = itemView.findViewById(R.id.FPName);
ccdesig = itemView.findViewById(R.id.FPDesig);
}
}
#Override
protected void onStop() {
super.onStop();
FBRA.stopListening();
}
FormActivity.java
public class FormActivity extends AppCompatActivity {
private EditText CName, PContact,PDesig, CCity;
private FirebaseDatabase mDatabase;
private Button Fbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
CName = findViewById(R.id.CompName);
PContact = findViewById(R.id.PContact);
PDesig = findViewById(R.id.PDesig);
CCity = findViewById(R.id.CCity);
mDatabase = FirebaseDatabase.getInstance();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
String dCName = CName.getText().toString().trim();
String dPContact = PContact.getText().toString().trim();
String dPDesig = PDesig.getText().toString().trim();
String dCCity = CCity.getText().toString().trim();
String name = CName.getText().toString().trim();
DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push();
mDbRef.child("cname").setValue(dCName);
mDbRef.child("pcontact").setValue(dPContact);
mDbRef.child("pdesig").setValue(dPDesig);
mDbRef.child("ccity").setValue(dCCity);
Toast.makeText(FormActivity.this, "Contact Submitted Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(FormActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
return super.onOptionsItemSelected(item);
}
}
Project.class
public class project {
String cname, pcontact, pdesig, ccity;
public project(){
}
public project(String cname, String pcontact, String pdesig, String ccity) {
this.cname = cname;
this.pcontact = pcontact;
this.pdesig = pdesig;
this.ccity = ccity;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getPcontact() {
return pcontact;
}
public void setPcontact(String pcontact) {
this.pcontact = pcontact;
}
public String getPdesig() {
return pdesig;
}
public void setPdesig(String pdesig) {
this.pdesig = pdesig;
}
public String getCcity() {
return ccity;
}
public void setCcity(String ccity) {
this.ccity = ccity;
}
}
HomeActivity.xml
<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:orientation="vertical"
tools:context=".HomeActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:id="#+id/ProjList"
/>
</RelativeLayout>
ProjRow.xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/FCName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorBlue"
android:maxLength="25"
android:paddingTop="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="16dp"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
<TextView
android:id="#+id/FCLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorDark"
android:layout_marginTop="13dp"
android:paddingTop="5dp"
android:textSize="14dp"
/>
<TextView
android:id="#+id/FPName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentLeft="true"
android:elegantTextHeight="true"
android:textStyle="bold"
android:textColor="#color/colorText"
android:paddingTop="5dp"
android:paddingRight="3dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="15dp"
/>
<TextView
android:id="#+id/FPDesig"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:padding="5dp"
android:textSize="14dp"
android:textColor="#color/colorNext"
android:elegantTextHeight="true"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
the code is working fine without error. But the intended value is not captured from database. If push() is removed from DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push(); , it works absolutely fine. but it overwrites on existing data while adding new data for the same 'name'. After adding push, the data are getting stored in sub child record. Please guide me how to refer and get back the data in recycleview adapter.
The each record stored under 'Contacts' before adding push()but overwrites when added a person for the same company.
After adding push() each record stored under company name with unique key.

How to display an image in a recyclerview?

I'm developing an android app using java and Firebase. In that I'm using a recycler view to display the images and other contents which are stored in Firebase database. When I run the program the other contents are displaying correctly but the image is not showing. This is my first time developing an android application so I'm confused.
Any help you can provide me to get this to work would be great.
Here is my code,
Adapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyMessageHolder> {
private StorageReference storage;
private Context context;
private ArrayList<profile> Messages;
public MessageAdapter(Context c , ArrayList<profile> p)
{
context = c;
Messages =p;
}
#NonNull
#Override
public MyMessageHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyMessageHolder(LayoutInflater.from(context).inflate(R.layout.activity_card_view,parent,false));
}
#Override
public void onBindViewHolder(#NonNull MyMessageHolder holder, int position) {
profile prof = Messages.get(position);
holder.name.setText(Messages.get(position).getTitle());
holder.description.setText(Messages.get(position).getDescription());
holder.date.setText(Messages.get(position).getDate());
//Picasso.get().load(Messages.get(position).getImage()).into(holder.image);
Picasso.get()
.load(prof.getImage())
.fit()
.centerCrop()
.into(holder.image);
}
#Override
public int getItemCount() {
return Messages.size();
}
class MyMessageHolder extends RecyclerView.ViewHolder
{
TextView name,description,date,time;
ImageView image;
public MyMessageHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.hTitle);
description = itemView.findViewById(R.id.hDescription);
date = itemView.findViewById(R.id.hDate);
time = itemView.findViewById(R.id.hTime);
image = itemView.findViewById(R.id.hImage);
}
}
}
Main activity class
class MainActivityHomePage extends AppCompatActivity {
private DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<profile> list;
MessageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference().child("Messages");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
profile p = dataSnapshot1.getValue(profile.class);
list.add(p);
}
adapter = new MessageAdapter( MainActivityHomePage.this,list);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityHomePage.this, "something wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
Model class
package com.eNotification.getnotify;
public class profile {
private String title;
private String description;
private String date;
private String image;
public profile() {
}
public profile(String title, String description, String date, String image) {
this.title = title;
this.description = description;
this.date = date;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
card view layout xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="170dp"
app:cardBackgroundColor="#android:color/white"
android:layout_marginTop="10dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"
app:cardPreventCornerOverlap="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/silver"
android:padding="5dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="260dp"
android:layout_height="match_parent"
android:padding="5dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/hTitle"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="8dp"
android:background="#color/lightSilver"
android:hint="Title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hTime" />
<TextView
android:id="#+id/hDescription"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="8dp"
android:background="#color/lightSilver"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hTitle" />
<TextView
android:id="#+id/hDate"
android:layout_width="136dp"
android:layout_height="30dp"
android:layout_marginEnd="4dp"
android:background="#color/lightSilver"
android:text="Date"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#id/hTime"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/hTime"
android:layout_width="116dp"
android:layout_height="30dp"
android:layout_marginStart="4dp"
android:background="#color/lightSilver"
android:text="Time"
app:layout_constraintStart_toEndOf="#id/hDate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<ImageView
android:id="#+id/hImage"
android:layout_width="160dp"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.834" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Recycler view 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:padding="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

Android RecyclerView with different layouts doesn't work

I am trying to implement a RecyclerView with two different layouts. In the MainActivity I first create ListItem object and add it to the list and then add that to the adapter, but it doesn't show. And also I am calling a method that creates ListItem object and adds it to the list and then notifies the adapter, but it still doesn't show. Here is my code so far:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="nl.iansoft.www.recyclerviewproblem.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp"
/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<ListItem> listItems;
private CustomAdapter customAdapter;
private RecyclerView rvList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvList = (RecyclerView)findViewById(R.id.rvList);
listItems = new ArrayList<>();
ListItem listItem = new ListItem("MyName", "MyLatsName", "MyEmail");
listItems.add(listItem);
customAdapter = new CustomAdapter(listItems);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
rvList.setLayoutManager(mLayoutManager);
rvList.setItemAnimator(new DefaultItemAnimator());
rvList.setAdapter(customAdapter);
addItemToTheList();
}
private void addItemToTheList(){
ListItem listItem = new ListItem("MyName", "MyLatsName", "MyEmail");
listItems.add(listItem);
customAdapter.notifyDataSetChanged();
}
}
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ListItem> listItems;
public class ListItem1ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvLastName;
public TextView tvEmail;
public ListItem1ViewHolder(View view) {
super(view);
tvName = (TextView) view.findViewById(R.id.tvName);
tvLastName = (TextView) view.findViewById(R.id.tvLastName);
tvEmail = (TextView) view.findViewById(R.id.tvEmail);
}
}
public class ListItem2ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName2;
public TextView tvLastName2;
public TextView tvEmail2;
public ListItem2ViewHolder(View view) {
super(view);
tvName2 = (TextView) view.findViewById(R.id.tvName2);
tvLastName2 = (TextView) view.findViewById(R.id.tvLastName2);
tvEmail2 = (TextView) view.findViewById(R.id.tvEmail2);
}
}
public CustomAdapter(ArrayList<ListItem> listItems) {
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if(viewType == 1){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item, parent, false);
return new CustomAdapter.ListItem1ViewHolder(itemView);
}else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item2, parent, false);
return new CustomAdapter.ListItem2ViewHolder(itemView);
}
}
#Override
public int getItemViewType(int position) {
if(listItems.get(position).getName().equals("MyName")){
return 1;
}else{
return 2;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
if(holder.getItemViewType() == 1) {
ListItem1ViewHolder listItem1ViewHolder = (ListItem1ViewHolder) holder;
listItem1ViewHolder.tvName.setText(listItem.getName());
listItem1ViewHolder.tvLastName.setText(listItem.getLastName());
listItem1ViewHolder.tvEmail.setText(listItem.getEmail());
}else{
ListItem2ViewHolder listItem2ViewHolder = (ListItem2ViewHolder)holder;
listItem2ViewHolder.tvName2.setText(listItem.getName());
listItem2ViewHolder.tvLastName2.setText(listItem.getLastName());
listItem2ViewHolder.tvEmail2.setText(listItem.getEmail());
}
}
#Override
public int getItemCount() {
return listItems.size();
}
}
ListItem.java
public class ListItem {
private String name;
private String lastName;
private String email;
public ListItem() {
}
public ListItem(String name, String lastName, String email) {
this.name = name;
this.lastName = lastName;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my_list_item2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Name2"
android:layout_marginTop="15dp"
android:padding="5dp"/>
<TextView
android:id="#+id/tvLastName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Last Name2"
android:layout_below="#+id/tvName2"
android:layout_marginTop="10dp"
android:padding="5dp" />
<TextView
android:id="#+id/tvEmail2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="my#email.com"
android:layout_below="#+id/tvLastName2"
android:layout_marginTop="5dp"
android:padding="5dp" />
</RelativeLayout>
my_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Name"
android:layout_marginTop="15dp"
android:padding="5dp"/>
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Last Name"
android:layout_below="#+id/tvName"
android:layout_marginTop="10dp"
android:padding="5dp" />
<TextView
android:id="#+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="my#email.com"
android:layout_below="#+id/tvLastName"
android:layout_marginTop="5dp"
android:padding="5dp" />
</RelativeLayout>
The issue is in ConstraintLayout. Because you haven't specified any constraints to your RecyclerView.
Either specify constraints, or move to another layout (e.g. FrameLayout).
But specifically in this case you do not need parent layout, because it is useless, as long as you have only RecyclerView in your view hierarchy.

How to remove item from ListView and sharedpreferences android studio?

i want to be able to do this to the code i have already I am new to programing please help.
- Add an icon the user can click (per item) to remove it
- When clicked that item on the list should be removed
-The item should be removed from storage as well (so it doesn't appear next time they load up the app)
here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String Log_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox CheckBox = (CheckBox) convertView.findViewById(R.id.CheckBox);
textView.setText(items.get(position).getDescription());
CheckBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
todolistmanager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if(json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit = savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
todoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return getDescription();
}
}
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"
/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:text="#string/txtEmpty"
android:gravity="center_horizontal"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/txtItem"
android:choiceMode="multipleChoice" >
</ListView>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
to_do_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<CheckBox
android:id="#+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<ListView
android:layout_weight="20"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/lblBtnDel" />
Step1: Create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/txtItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text" />
<Button
android:id="#+id/btnAdd"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txtItem"
android:text="Add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/lvTodo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" />
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:text="No data"
android:visibility="invisible" />
</RelativeLayout>
<Button
android:id="#+id/btnDel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Step2: Create to todo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvTodoName"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Learn Android"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cbChooseTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Step3: Define Object Todo
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem(String description, boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isComplete() {
return isComplete;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Step4: Create TodoItemAdapter class
public class TodoItemAdapter extends ArrayAdapter<ToDoItem> {
private ArrayList<ToDoItem> arrayListTodo;
private LayoutInflater layoutInflater;
public TodoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) {
super(context, resource, objects);
this.arrayListTodo = objects;
this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.todo_item, parent,false);
holder.tvTodoName = (TextView)convertView.findViewById(R.id.tvTodoName);
holder.cbTodoChoose = (CheckBox)convertView.findViewById(R.id.cbChooseTodo);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
final ToDoItem toDoItem = arrayListTodo.get(position);
holder.tvTodoName.setText(toDoItem.getDescription());
holder.cbTodoChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toDoItem.setComplete(isChecked);
}
});
holder.cbTodoChoose.setChecked(toDoItem.isComplete());
return convertView;
}
public static class ViewHolder{
public TextView tvTodoName;
public CheckBox cbTodoChoose;
}
}
Step5: Process on the MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView lvTodoItem;
private ArrayList<ToDoItem> toDoItems;
private TodoItemAdapter todoItemAdapter;
private Button btnDel;
private Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData(){
toDoItems = new ArrayList<>();
todoItemAdapter = new TodoItemAdapter(MainActivity.this, R.layout.todo_item, toDoItems);
lvTodoItem = (ListView)findViewById(R.id.lvTodo);
lvTodoItem.setAdapter(todoItemAdapter);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnDel = (Button)findViewById(R.id.btnDel);
btnAdd.setOnClickListener(this);
btnDel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnAdd:
addTodoItem();
break;
case R.id.btnDel:
deleteTodoItem();
break;
}
}
private void addTodoItem() {
}
private void deleteTodoItem() {
for (int i= toDoItems.size()-1; i>=0 ; i--){
ToDoItem toDoItem = toDoItems.get(i);
if (toDoItem.isComplete()){
toDoItems.remove(i);
}
}
todoItemAdapter.notifyDataSetChanged();
}
}
It is working fine. Thanks.

Can't display items in RecyclerView

I am having problems in displaying cards dynamically from a recycler view. Here's my code.
CardActivity.java
public class CardActivity extends AppCompatActivity {
CardAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<CardModel> data = new ArrayList<>();
public static String IMGS[] = {
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12540788_486126334923939_641652950626105372_n.jpg?oh=520090fa887ded912ddb7086fc69fc93&oe=57A04969",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/12973436_521081094761796_6679453535369186441_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/12191632_465602330309673_5460380145671805117_n.jpg?oh=51811b46395fee6e4bdb5394e6725591&oe=57D35DC3",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/10628472_397420133794560_5446805358922772021_n.jpg?oh=f23ab8761e05b2a50d0d0c9dec4d365b&oe=57DBF1CC",
"https://scontent.fmnl4-2.fna.fbcdn.net/t31.0-8/10697227_314766035393304_2937143993369666506_o.jpg",
"https://scontent.fmnl4-2.fna.fbcdn.net/v/t1.0-9/13133194_10154674163886840_3764712620850385571_n.jpg?oh=252cedf88040188f12ce99c29f3dd47e&oe=57DD7474"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
for (int i = 0; i < IMGS.length; i++) {
CardModel cardModel = new CardModel();
cardModel.setTitle("Card Title: " + i);
cardModel.setDescription("This is a card description");
cardModel.setUrl(IMGS[i]);
data.add(cardModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Cards");
mRecyclerView = (RecyclerView) findViewById(R.id.cards);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CardActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
mAdapter = new CardAdapter(CardActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
}
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}
CardModel.java
public class CardModel {
String url,title,description;
public CardModel() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardHolder> {
private LayoutInflater inflater;
Context context;
List<CardModel> data = new ArrayList<>();
public CardAdapter(Context context, List<CardModel> data){
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
#Override
public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_layout,parent,false);
CardHolder cardHolder = new CardHolder(view);
return cardHolder;
}
#Override
public void onBindViewHolder(CardHolder holder, int position) {
holder.cardTitle.setText(data.get(position).getTitle());
holder.cardDescription.setText(data.get(position).getDescription());
Glide.with(context).load(data.get(position).getUrl())
.fitCenter()
.into(holder.cardImage);
}
#Override
public int getItemCount() {
return 0;
}
public static class CardHolder extends RecyclerView.ViewHolder {
ImageView cardImage;
TextView cardTitle;
TextView cardDescription;
public CardHolder(View cardView) {
super(cardView);
cardImage = (ImageView) cardView.findViewById(R.id.card_image);
cardTitle = (TextView) cardView.findViewById(R.id.card_title);
cardDescription = (TextView) cardView.findViewById(R.id.card_description);
}
}
}
activity_card.xml
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.braudy.android.mesasixprofiler.CardActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#FFFFFF"
android:padding="10dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#ffffff">
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:alpha=".7"
android:id="#+id/card_image"
android:background="#ffff66"
android:src="#drawable/img1"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Braudy"
android:paddingLeft="15dp"
android:textColor="#FFFFFF"
android:background="#707070"
android:alpha=".8"
android:textSize="25sp"
android:id="#+id/card_title"
android:layout_alignBottom="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="This is a description"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:textColor="#A9A9AF"
android:textSize="15sp"
android:id="#+id/card_description"
android:layout_below="#+id/card_image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Change this
#Override
public int getItemCount() {
return 0;
}
to
#Override
public int getItemCount() {
return data.size();
}
change here-
#Override
public int getItemCount() {
return data.size();
}
You have to declare how much views you want to inflate in your view.

Categories

Resources