How to pass data from activity to RecyclerViewAdapter class - android

I have been used Intent to save the data that I want to pass.. this is in login page..
String name = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), Posting.class);
intent.putExtra("myname", name);
this username I want to pass it from login page to my RecyclerView layout by clicking on Add Button in Posting class:
By clicking on AddButton the username should appear in each CardView.
here is the posting class that have AddButton:
public class Posting extends ActionBarActivity {
private RecyclerView myRecyclerView;
private LinearLayoutManager linearLayoutManager;
private RecyclerViewAdapter myRecyclerViewAdapter;
EditText nameField;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posting);
myRecyclerView = (RecyclerView) findViewById(R.id.myrecyclerview);
btnAdd = (Button) findViewById(R.id.addbutton);
Toolbar my_toolbars = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(my_toolbars);
getSupportActionBar().setTitle(R.string.title);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
myRecyclerViewAdapter = new RecyclerViewAdapter(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
nameField = (EditText) findViewById(R.id.namefield);
btnAdd = (Button) findViewById(R.id.addbutton);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
if (!newName.equals("")) {
myRecyclerViewAdapter.add(0, newName);
TextView textView = (TextView) findViewById(R.id.display);
Intent intent = getIntent();
String name = intent.getStringExtra("myname");
textView.setText(name);
}
}
});
}
and this is the layout of the cardView.
<?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:scrollbars="vertical"
android:layout_margin="10dp"
card_view:cardCornerRadius="20sp"
card_view:cardElevation="5sp">
<TextView
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="8pt"
android:text="i" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_margin="25dp"/>
<TextView
android:id="#+id/card_item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="8pt"
android:layout_marginTop="30dp"/>
I want to pass it from login page to this page through TextView with id="username".
how can this be done?

//in posting Activity
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
if (!newName.equals("")) {
myRecyclerViewAdapter = new RecyclerViewAdapter(this,newName);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
}
});
In RecyclerViewAdapter
//Create Constructor like below:
String name;
Activity context;
public RecyclerViewAdapter(Activity activity,String newName){
this.context=activity;
this.name= newName;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
holder.username.setText(name);
}

Related

all of items are not list up in Recycler viewer

i created Recycler view that shows the item list, however, only first top 10 are shown if i drag down the list repeat the randomly first 1~10 items, it should be shown like that
1
2
3
4
5
6
7
8
9
10
11
12
13
....
but
1
2
3
4
5
6
7
8
9
10 (till here good)
5
3
6
....(only repeating 1~10 number)
i attached the code, can someone get me the advice??
private RecyclerView mItemRecyclerView;
private LinearLayoutManager mLayoutManager;
private ItemAdapter mAdapter;
private TextView mTitleTextView;
private TextView mCostTextView;
private Button mBuyButton;
private Button mSellButton;
private Button mUse;
private Button mLeaveButton;
private GameData gmd;
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.recycler_view);
gmd = (GameData) getIntent().getSerializableExtra("gamedataToMarket");
mItemRecyclerView = findViewById(R.id.item_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mItemRecyclerView.setLayoutManager(mLayoutManager);
List<Item> items = gmd.getItems();
mAdapter = new ItemAdapter(items);
mItemRecyclerView.setAdapter(mAdapter);
mLeaveButton = findViewById(R.id.leave_Button);
mLeaveButton.setText(R.string.leave);
mLeaveButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent rtn = new Intent();
rtn.putExtra("gameDataReturnFromMarKet",gmd);
setResult(1,rtn);
Toast.makeText(marketActivity.this, "back to navigation from market", Toast.LENGTH_SHORT).show();
finish();
}
});
FragmentManager fm2 = getSupportFragmentManager();
Fragment fragment2 = fm2.findFragmentById(R.id.status_recycler);
if(fragment2 == null){
fragment2 = new status_fragment();
fm2.beginTransaction()
.add(R.id.status_recycler,fragment2)
.commit();
}
}
private class ItemHolder extends RecyclerView.ViewHolder{
private Item mItems;
public ItemHolder(View view) {
super(view);
mTitleTextView = (TextView) itemView.findViewById(R.id.item_name);
mCostTextView = (TextView) itemView.findViewById(R.id.item_cost);
mBuyButton = (Button) itemView.findViewById(R.id.button_1_option);
mBuyButton.setText(R.string.bought);
mBuyButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(marketActivity.this, R.string.bought, Toast.LENGTH_SHORT).show();
}
});
mSellButton = (Button) itemView.findViewById(R.id.button_2_option);
mSellButton.setText(R.string.sold);
mSellButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(marketActivity.this, R.string.sold, Toast.LENGTH_SHORT).show(); // function for sell item
}
});
mUse = (Button) itemView.findViewById(R.id.button_3_option);
mUse.setText(R.string.use);
mUse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(marketActivity.this, R.string.use, Toast.LENGTH_SHORT).show();
}
});
}
public void bind(Item item) {
mItems = item;
mTitleTextView.setText(item.getDescription());
mCostTextView.setText(String.valueOf(item.getValue()));
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {
private List<Item> items;
public ItemAdapter(List<Item> item) {
items = item;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.holdingview,parent,false);
return new ItemHolder(v);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
holder.bind(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="0.8"
android:padding="1dp"
android:text="item name" />
<TextView
android:id="#+id/item_cost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:padding="1dp"
android:text="cost" />
<Button
android:id="#+id/button_1_option"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/button_2_option"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/button_3_option"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
You have to make some changes in your code like this:
In ItemHolder class you are passing "view" in super method but getting by id using
"itemView".You have to find the id of view by using the same parameter that you
passing in super method.
so change all your findViewById like this:
mTitleTextView = (TextView) view.findViewById(R.id.item_name);
mCostTextView = (TextView) view.findViewById(R.id.item_cost);
You are declaring views (TextView and Button which you are using to populate data) in
activity and geting id in viewHolder.You have to declare them inside the viewholder.
In your case do it like this :
private class ItemHolder extends RecyclerView.ViewHolder {
private TextView mTitleTextView;
private TextView mCostTextView;
private Button mBuyButton;
private Button mSellButton;
private Button mUse;
public ItemHolder(View view) {
super(view);
mTitleTextView = (TextView) view.findViewById(R.id.item_name);
mCostTextView = (TextView) view.findViewById(R.id.item_cost);
mBuyButton = (Button) view.findViewById(R.id.button_1_option);
mSellButton = (Button) view.findViewById(R.id.button_2_option);
mUse = (Button) view.findViewById(R.id.button_3_option);
}
}

onClick incorrectly being Registered

I tried to implement an onClick method to my card recyclerView. When I click the card nothing happens but when I click the gap between the cards the intended action is performed. This was confirmed when as I tested this by increasing the spacing between the cards. What did I do wrong and how do I change my code to fix this problem?
This is the Adapter
public class JobListRecyclerAdapter extends RecyclerView.Adapter<JobListRecyclerAdapter.jobViewHolder> {
private ArrayList<JobClass> jobClassList;
private static OnItemClickListener clickListener;
public JobListRecyclerAdapter(ArrayList<JobClass> rList) {
this.jobClassList = rList;
}
#Override
public int getItemCount() {
if(jobClassList == null){return 0;}
return jobClassList.size();
}
#Override
public jobViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.job_list_card, viewGroup, false);
return new jobViewHolder(itemView);
}
#Override
public void onBindViewHolder(jobViewHolder jobViewHolder, int position) {
JobClass ci = jobClassList.get(position);
jobViewHolder.jName.setText("Name: "+ci.getmJobNum());
jobViewHolder.jDate.setText("Quantity: "+ci.getmJobDate());
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public static class jobViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView jName;
protected TextView jDate;;
public jobViewHolder(View j) {
super(j);
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
itemView.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
}
#Override
public void onClick(View view) {
if (clickListener != null) {clickListener.onClick(view, getLayoutPosition());}
}
}
}
This is the Activity
public class JobList extends Fragment implements OnItemClickListener {
public JobList() {
}
public static JobList newInstance() {
JobList fragment = new JobList();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_job_list, container, false);
final RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.job_list_recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(llm);
final ArrayList<JobClass> joblistclass = new ArrayList<>();
/*
// Create a new Adapter
final ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1);
*/
// Get a reference to the todoItems child items it the database
//String userPath = ((GlobalData) getActivity().getApplication()).getUserPath() +"JOBS";
//final DatabaseReference myRef = database.getReference(userPath);
// final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS/04950F4AE53F80/JOBS");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference jobsRef = rootRef
.child("USERS")
.child("04950F4AE53F80")
.child("JOBS");
// Assign a listener to detect changes to the child items
// of the database reference.
// myRef.addValueEventListener(new ValueEventListener() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String jobno = ds.child("JOBOVERVIEW").child("jobNum").getValue(String.class);
JobClass jblst = ds.child("JOBOVERVIEW").getValue(JobClass.class);
joblistclass.add(jblst);
((GlobalData) getContext().getApplicationContext()).saveJobNum(jobno);
}
final JobListRecyclerAdapter adapterb = new JobListRecyclerAdapter(joblistclass);
recyclerView.setAdapter(adapterb);
adapterb.setClickListener(JobList.this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
jobsRef.addListenerForSingleValueEvent(eventListener);
///to send to next page
Button nextPage = (Button) rootView.findViewById(R.id.addNewJob);
// Capture button clicks
nextPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start NewActivity.class
Intent myIntent = new Intent(getContext(), JobForm.class);
startActivity(myIntent);
}
});
return rootView;
}
#Override
public void onClick(View view, int position) {
ArrayList<String> nameArray = ((GlobalData) getActivity().getApplication()).getJobNums();
String name = nameArray.get(position);
((GlobalData) getActivity().getApplication()).setJobId(name);
Toast.makeText(getContext(), name,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(getContext(), Main2Activity.class);
startActivity(intent);
}
}
Card View XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.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"
app:cardUseCompatPadding="true"
android:id="#+id/job_card_layout"
android:layout_marginBottom="4dp"
android:clickable="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:id="#+id/job_linear_layout"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="9dp"
android:clickable="true"
>
<TextView
android:id="#+id/job_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:clickable="true"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/job_due_date"
android:layout_toRightOf="#+id/job_name"
android:clickable="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
Please use below xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:id="#+id/job_card_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:id="#+id/job_linear_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginBottom="9dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/job_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="20sp" />
<TextView
android:id="#+id/job_due_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/job_name" />
</LinearLayout>
Note: android:clickable="true" has to be removed from your xml file.
Also, use
j.setOnClickListener(this);
instead of
itemView.setOnClickListener(this);
You don't have itemView field in your adapter or viewHolder as I can see. Maybe jobViewHolder should look like this:
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
j.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
Maybe your child view is placed at foreground and take all interactive from user. Let try this code in your child view xml.
android:duplicateParentState="true"
Update jobViewHolder class
Change following line
itemView.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
to
j.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
OR
j.setOnClickListener(this); // bind the listener
NOTE: If this doesn't work then you are referring wrong id i.e. job_card_layout
Updated JobViewHolder.java
public static class jobViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView jName;
protected TextView jDate;;
public jobViewHolder(View j) {
super(j);
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
itemView.setOnClickListener(this); // bind the listener
}
#Override
public void onClick(View view) {
if (clickListener != null) {clickListener.onClick(view, getLayoutPosition());}
}
}

RecyclerView doesn't load items on first start of activity

Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708
The Item i am spawning in:
<?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:card_view="http://schemas.android.com/tools"
android:id="#+id/show_chat_single_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="70dp"
app:cardBackgroundColor="#dcdada"
app:cardCornerRadius="0dp"
app:contentPadding="3dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="2dp"
card_view:cardUseCompatPadding="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/chat_persion_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/chat_persion_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="0dp"
android:text="Name"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintLeft_toRightOf="#+id/chat_persion_image"
app:layout_constraintTop_toTopOf="#+id/chat_persion_image" />
<TextView
android:id="#+id/chat_persion_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginTop="8dp"
android:text="Email"
app:layout_constraintLeft_toLeftOf="#+id/chat_persion_name"
app:layout_constraintTop_toBottomOf="#+id/chat_persion_name" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
My conversation layout:
<?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"
android:id="#+id/msgs_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:theme="#style/AppTheme2"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/active_chats"
android:layout_width="match_parent"
android:layout_height="510dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="57dp">
</android.support.v7.widget.RecyclerView>
<include
android:id="#+id/include2"
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
My Adapter:
public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
private ArrayList<User> mUsers;
private Context mContext;
public ActiveChatConvo(ArrayList<User> photos,Context dick) {
mUsers = photos;
mContext = dick;
}
private Context getContext() {
return mContext;
}
#Override
public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
User user = mUsers.get(position);
// Set item views based on your views and data model
TextView name = holder.mItemName;
name.setText(user.getName());
TextView description = holder.mItemDescription;
description.setText(user.getEmail());
ImageView pic = holder.mItemImage;
Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mItemImage;
private TextView mItemName;
private TextView mItemDescription;
private LinearLayout layout;
final LinearLayout.LayoutParams params;
public ViewHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = itemView.getContext();
Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
//showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
context.startActivity(showChatIntent);
}
}
}
My main class
public class ConnectionsActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mViewPager;
private TextView person_name,person_email;
private RecyclerView recyclerView;
private DatabaseReference mRef;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<User> users;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connections);
//Database
mRef = FirebaseDatabase.getInstance().getReference("Users");
mRef.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
users = new ArrayList<>();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String name = postSnapshot.child("Name").getValue(String.class);
String email = postSnapshot.child("Email").getValue(String.class);
String pic = postSnapshot.child("image").getValue(String.class);
users.add(new User(name,email,pic));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Recycler View
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
//VIEWS
toolbar = (Toolbar) findViewById(R.id.tToolbar);
if (toolbar != null)
setSupportActionBar(toolbar);
ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);
profileActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
startActivity(profileActivity);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
homeActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
startActivity(home);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
}
}
So if the recyclerView Activity is the first activity I visit then it will not create the items.
Firebase is synchronize so it doesn't block the main thread of your application, that mean that your application continue executing, you need to notify the adapter after firebase finishing his job by using adapter.notifiyDatasetChanged() after the for loop
Replace this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
with this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
You need to set adapter after you set LayoutManager.
In my case I managed to solve it I found a way to start FirebaseDatabase before opening the activity and added the cod
adapter.notifyDataSetChanged();
and then I started the firebase before opening it with this
FirebaseDatabase.getInstance().getReference().keepSynced(true);
You can use Boolean button to check if it is true adapter is made

Recycler View: java.lang.NullPointerException - android.widget.EditText.getText() on null object reference

I am getting the following exception while i'm try to pass data to the recycler view:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.laraib.dynamicdataapp, PID: 31538
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.laraib.dynamicdataapp.MainActivity$1.onClick(MainActivity.java:55)
at android.view.View.performClick(View.java:4766)
at android.view.View$PerformClick.run(View.java:19683)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5538)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I have created a fragment in the main activty where the fragment is
hosting the recycler view and an event adapter class is attched to the
recycler view to display the data. The data has to be passed
dynamically. When the user clicks on the floating action bar button, a
pop up window will open where the user has to input a value in the
edit text field and on pressing ok button the data will be added to
the fragment recycler view.
Here's my code:
EventFragment.java
public class EventFragment extends Fragment{
List<Event> event=new ArrayList<>();
EventAdapter adapter;
FloatingActionButton fab;
public EventFragment() {}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_friend_event, container, false);
final RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.event_recycler_view);
fab = (FloatingActionButton) rootView.findViewById(R.id.floating_bar_event);
rv.setHasFixedSize(true);
LinearLayoutManager ll = new LinearLayoutManager(getActivity());
rv.setLayoutManager(ll);
rv.setItemAnimator(new DefaultItemAnimator());
adapter = new EventAdapter(event,this.getActivity());
rv.setAdapter(adapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity ) getActivity()).displayDialog();
}
});
return rootView;
}}
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText event_name;
EditText event_text;
Button saveButton;
RecyclerView rv;
EventAdapter adapter;
List<Event> event=new ArrayList<>();
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
Fragment fragmentEvent = new EventFragment();
setTitle("Home");
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentEvent).commit();
}
public void displayDialog()
{
Dialog dialog = new Dialog(this);
dialog.setTitle("Add Event");
dialog.setContentView(R.layout.popup_events);
event_text = (EditText) findViewById(R.id.editText_msg);
event_name = (EditText) findViewById(R.id.editText_name);
rv = (RecyclerView) findViewById(R.id.event_recycler_view);
saveButton = (Button) dialog.findViewById(R.id.button_ok);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// save(event_name.getText().toString());
s = event_name.getText().toString();
event_name.setText("");
adapter = new EventAdapter(EventData.getEventData(s),MainActivity.this);
Log.d("username", event_name.getText().toString());
rv.setAdapter(adapter);
}
});
dialog.show();
}}
EventData.java
public class EventData {
public static List<Event> getEventData(String e)
{
List<Event> data = new ArrayList<>();
Event item = new Event();
item.setEventText(e);
data.add(item);
Log.d("method invoked", e);
return data;
}
}
EventAdapter.java
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private List<Event> eventData;
private LayoutInflater inflater;
public EventAdapter(List<Event> eventData, Context context){
inflater = LayoutInflater.from(context);
this.eventData = eventData;
}
#Override
public EventViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_events, parent, false);
EventAdapter.EventViewHolder vh = new EventAdapter.EventViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(EventViewHolder holder, final int position) {
holder.eventTextView.setText(eventData.get(position).getEventText().toString());
Log.i("CALL","Button adapter is invoked");
}
#Override
public int getItemCount() {
return eventData.size();
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
public CardView eventCardView;
public TextView eventTextView;
public EventViewHolder(View itemView)
{
super(itemView);
eventCardView = (CardView) itemView.findViewById(R.id.event_card_view);
eventTextView = (TextView) itemView.findViewById(R.id.event_text);
}
}
public void add(Event item,int position)
{
eventData.add(item);
notifyItemInserted(position);
}
public void remove(Event item)
{
int position = eventData.indexOf(item);
eventData.remove(position);
notifyItemRemoved(position);
}}
popup_event.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_height="10dp"
android:layout_width="match_parent"></View>
<TextView
android:layout_height="30dp"
android:layout_width="match_parent"
android:text="Add Event"
android:textSize="25dp"
android:textAlignment="center"
/>
<View
android:layout_height="10dp"
android:layout_width="match_parent"></View>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Name:"
android:textSize="20dp"
android:id="#+id/textView_name"
android:layout_column="1"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/editText_name"
android:layout_column="2"/>
</TableRow>
<View
android:layout_height="10dp"
android:layout_width="match_parent"></View>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Date:"
android:textSize="20dp"
android:id="#+id/textView_msg"
android:layout_column="1"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/editText_msg"
android:layout_column="2"/>
</TableRow>
<View
android:layout_height="10dp"
android:layout_width="match_parent"></View>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/button_ok"
android:layout_column="3" />
</TableRow>
</TableLayout>
The simple way is: using a Handler to send/receive msg when user taps on button Ok.
In your activity that hosted recycler view
public static final int MSG_USER_INPUT = 0x01;
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_USER_INPUT:
String userInputStr = msg.obj.toString();
// refine your data here, ex: mAdapter.setData();
// remember to call notifyDataSetChanged() in adapter
break;
default:
//
break;
}
}
};
Pass this handler to your popup constructor
Then in OnClick of Ok button
Message message = new Message();
message.obj = mEdtText.getText().toString();
message.what = YourActivity.MSG_USER_INPUT;
mHandler.sendMessage(message);
Hope this help!
Farther solution, imo, you should try RxJava!

ListView not showing text on items

I want to display text input from an editText and show it in a listView using an ArrayAdapter, when clicking a button, the listView does gets an item added but without the text :
here is the code:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.blink.blink.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<EditText
android:layout_width="280dp"
android:layout_height="60dp"
android:hint="Type a quote .. "
android:id="#+id/quoteField" />
<Button
android:layout_width="wrap_content"
android:layout_height="60dp"
android:text="Add Quote"
android:id="#+id/addQuote"
android:fontFamily="sans-serif-condensed"
android:background="#f6546a"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/quoteField" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quotelistView"
android:foreground="#f6546a"/>
</LinearLayout>
and :
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter();
quoteField.setText(" ");
}
});
}
private void SetAdapter()
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
}
}
You do not need to reset the adapter everytime you change the data in the array. What you should do is keep a reference to the adapter and call adapter.notifyDataSetChanged() when you change the data in the list
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(adapter);
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
adapter.notifyDataSetChanged();
quoteField.setText(" ");
}
});
}
}
Try it!
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter(quotesArrayList);
quoteField.setText(" ");
}
});
}
private void SetAdapter(ArrayList<String> quotesArrayList)
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
}

Categories

Resources