Passing values from recyclerview cardview to deatilactivity onitemclick - android

I'm new to android development, I have been trying to pass values from recyclerview cardview to detailActivity, after searching for couple of hours I came up with this code, before implementing this code I was able to view all the cardview on MainActivity, Now when I implemented this code app is crashing when I start the app, event log.
This is my Fragment which contain Firebaserecycler Adapter and viewholder class:
public class MakingFragment extends Fragment {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private TextView tvNoMovies;
Context c;
ArrayList<Food> spacecrafts;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "53";
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.making,container,false);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
tvNoMovies = (TextView) v.findViewById(R.id.tv_no_movies);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager.setReverseLayout(true); // to reverse the items updating on recycleview
mLayoutManager.setStackFromEnd(true); // to scroll from top when layout is reversed
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("food").getRef()
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, final Food model, int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvFoodName.setText(model.getFoodName());
viewHolder.ratingBar.setRating(model.getFoodRating());
viewHolder.tvFoodCategory.setText(model.getFoodCategory());
viewHolder.tvFoodAvailableUpto.setText(model.getFoodAvailableUpto());
viewHolder.tvFoodPrice.setText(model.getFoodPrice());
Picasso.with(getActivity().getApplicationContext()).load(model.getFoodPoster()).into(viewHolder.ivFoodPoster);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
//OPEN DETAI ACTIVITY
openDetailActivity(model.getFoodName(),model.getFoodCategory(),model.getFoodAvailableUpto(),model.getFoodPrice());
}
});
}
#Override
public int getItemCount() {
return spacecrafts.size();
}
//OPEN DETAIL ACTIVITY
private void openDetailActivity(String...details)
{
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("TITLE_KEY",details[0]);
i.putExtra("CAT_KEY",details[1]);
i.putExtra("AVAIL_KEY",details[2]);
i.putExtra("PRI_KEY",details[3]);
c.startActivity(i);
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchactivity=new Intent(getActivity().getApplicationContext(),AddFoodDetailsActivity.class);
startActivity(launchactivity);
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
return v;
}
public void onBackPressed() {
getActivity().onBackPressed();
if (fab.getVisibility() == View.GONE)
fab.setVisibility(View.VISIBLE);
}
//ViewHolder for our Firebase UI
public static class FoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvFoodName;
RatingBar ratingBar;
ImageView ivFoodPoster;
TextView tvFoodCategory;
TextView tvFoodAvailableUpto;
TextView tvFoodPrice;
ImageView ivNextArrow;
ItemClickListener itemClickListener;
public FoodViewHolder(View v) {
super(v);
tvFoodName = (TextView) v.findViewById(R.id.tvName);
ratingBar = (RatingBar) v.findViewById(R.id.rating_bar);
ivFoodPoster = (ImageView) v.findViewById(R.id.imgThumb);
tvFoodCategory = (TextView) v.findViewById(R.id.tvCategory);
tvFoodAvailableUpto= (TextView) v.findViewById(R.id.tvavailable);
tvFoodPrice = (TextView) v.findViewById(R.id.tvprice);
ivNextArrow = (ImageView) v.findViewById(R.id.NextArrow);
v.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(this.getLayoutPosition());
}
}
}
This is my DetailActivity
public class DetailActivity extends AppCompatActivity {
TextView nameTxt,catTxt,availTxt,priceTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nameTxt = (TextView) findViewById(R.id.titleTxt);
catTxt= (TextView) findViewById(R.id.catTxt);
availTxt = (TextView) findViewById(R.id.availTxt);
priceTxt = (TextView) findViewById(R.id.pricesTxt);
//GET INTENT
Intent i=this.getIntent();
//RECEIVE DATA
String title=i.getExtras().getString("TITLE_KEY");
String cat=i.getExtras().getString("CAT_KEY");
String avail=i.getExtras().getString("AVAIL_KEY");
String price=i.getExtras().getString("PRI_KEY");
//BIND DATA
nameTxt.setText(title);
catTxt.setText(cat);
availTxt.setText(avail);
priceTxt.setText(price);
}
}
Please help me out, thank you.

Initialize the arraylist in oncreate()
spacecrafts= new ArrayList<>();
also these in oncreate()
database = FirebaseDatabase.getInstance();
mDatabaseReference = database.getReference();
and check spacecrafts is null or not

Related

Adding recyclerview

I would like to create a simple application which has two activities. Activity A has recyclerview, and Activity B uploads the input data of edittexts. Creating recyclerview and passing data work well, but the view is not created more than 1. I would like to know what did I do wrong.
Activity A which has recyclerview.
public class MainActivity extends AppCompatActivity {
private ArrayList<MainData> list;
private MainAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
list = (ArrayList<MainData>) getIntent().getSerializableExtra("list");
adapter = new MainAdapter(list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Activity B which uploads data.
public class upload extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(upload.this, MainActivity.class);
ArrayList<MainData> list = new ArrayList<>();
EditText edit = (EditText) findViewById(R.id.edittext_name);
EditText edit_main = (EditText) findViewById(R.id.edittext_main);
list.add(new MainData(edit.getText().toString(), edit_main.getText().toString()));
intent.putExtra("list",list);
startActivity(intent);
finish();
}
});
Adapter :
public MainAdapter.CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
public void onBindViewHolder(#NonNull MainAdapter.CustomViewHolder holder, int position) {
//holder.iv_profile.setImageResource(list.get(position).getIv_profile());
holder.tv_name.setText(list.get(position).getTv_name());
holder.tv_content.setText(list.get(position).getTv_content());
holder.itemView.setTag(position);
#Override
public int getItemCount() {
return (null != list ? list.size() : 0);
}
public void remove(int position) {
try {
list.remove(position); //
notifyItemRemoved(position);
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView iv_profile;
protected TextView tv_name;
protected TextView tv_content;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
this.iv_profile = (ImageView) itemView.findViewById(R.id.iv_profile);
this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
this.tv_content = (TextView) itemView.findViewById(R.id.tv_content);
}
}

android recyclerview scroll making mess in chat using firebase

I'm simply implementing a RecyclerView for showing chat between two. Everything is working fine but there is one problem when I am scrolling up and again scrolling down the direction of sender message goes left(GRAVITY) which I have set only for the received ones. Please look the code below hope u will understand.
Screenshot before scrolling.
Screenshot after scrolling.
Here's my RecycleActivity.java
public class RecycleActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference databaseReference,temp;
EditText editText;
Button btnSend;
public static String nameOFUser = "";
LinearLayoutManager linearLayoutManager;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainer);
sharedPreferences = getSharedPreferences("MyLoginPref",MODE_PRIVATE);
nameOFUser = sharedPreferences.getString("name","");
Log.e("name",nameOFUser);
recyclerView = (RecyclerView) findViewById(R.id.recyclerid);
recyclerView.setHasFixedSize(true);
linearLayoutManager= new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
databaseReference = FirebaseDatabase.getInstance().getReference().child("msg");
editText = (EditText) findViewById(R.id.edittextmessagetosend);
btnSend = (Button) findViewById(R.id.button41);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
temp=databaseReference.push();
temp.child("name").setValue(nameOFUser);
temp.child("message").setValue(editText.getText().toString().trim());
editText.setText("");
recyclerView.setLayoutManager(linearLayoutManager);
}
});
}
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<MessageBlog,MessageHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<MessageBlog, MessageHolder>(
MessageBlog.class,R.layout.message_row,MessageHolder.class,databaseReference
) {
#Override
protected void populateViewHolder(MessageHolder viewHolder, MessageBlog model, int position) {
String name = model.getName();
viewHolder.setSender(name);
viewHolder.SetMessage(model.getMessage());
viewHolder.setDirection(name);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recyclerView.smoothScrollToPosition(firebaseRecyclerAdapter.getItemCount());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The ViewHolder.java
public static class MessageHolder extends RecyclerView.ViewHolder{
View view;
LinearLayout lay,linearLayoutback;
CardView cardViewreal;
DatabaseReference mdatabase;
public MessageHolder(View itemView) {
super(itemView);
view = itemView;
linearLayoutback = (LinearLayout)
itemView.findViewById(R.id.linearlayoutback);
mdatabase=FirebaseDatabase.getInstance().getReference().child("msg");
lay = (LinearLayout) itemView.findViewById(R.id.idcardview);
cardViewreal = (CardView) itemView.findViewById(R.id.idrealcard);
}
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
} else {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
}
}
void setSender(String sender){
TextView tvsender = (TextView) view.findViewById(R.id.senderidtv);
tvsender.setText(sender);
}
void SetMessage(String message){
TextView tvmessage = (TextView) view.findViewById(R.id.messageidtv);
tvmessage.setText(message);
}
}
Check your set direction method. It always sets direction to the left
void setDirection(final String name){
if(!name.equalsIgnoreCase(nameOFUser)) {
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#ffffff"));
//linearLayoutback.setBackgroundResource(R.drawable.white);
}
else{
lay.setGravity(Gravity.LEFT);
cardViewreal.setCardBackgroundColor(Color.parseColor("#f5f4f5"));
// linearLayoutback.setBackgroundResource(R.drawable.white);
}

How to swipe to delete on RecyclerView?

What I have here a History page that displays the requests the user have accepted or posted. I was able to successfully put a button for the user to delete all of the history the user has. Now I want the user to be able to delete a history one at a time by swiping it.
HistoryFragment.java
RecyclerView rView;
Button clear;
DatabaseReference dRef;
LinearLayoutManager llm;
String id;
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history, container, false);
FirebaseUser fu = FirebaseAuth.getInstance().getCurrentUser();
id = fu.getUid();
dRef = FirebaseDatabase.getInstance().getReference().child("History"+id);
clear = (Button) myView.findViewById(R.id.clear);
rView = (RecyclerView) myView.findViewById(R.id.history_list);
rView.setHasFixedSize(true);
llm = new LinearLayoutManager(getActivity());
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
rView.setLayoutManager(llm);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dRef.removeValue();
}
});
return myView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<HistoryData, HistoryFragment.RequestViewHolder> fra = new FirebaseRecyclerAdapter<HistoryData, HistoryFragment.RequestViewHolder>(
HistoryData.class,
R.layout.historylistview,
HistoryFragment.RequestViewHolder.class,
dRef
) {
#Override
protected void populateViewHolder(final HistoryFragment.RequestViewHolder viewHolder, HistoryData model, final int position) {
viewHolder.setTrans(model.getTrans());
viewHolder.setRequestDeadline(model.getRequestDeadline());
viewHolder.setRequestDescription(model.getRequestDescription());
viewHolder.setDateTimeAccepted(model.getDateTimeAccepted());
viewHolder.setRequestLocation(model.getRequestLocation());
viewHolder.setProfile(getApplicationContext() ,model.getProfile());
}
};
rView.setAdapter(fra);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder{
View myView;
public RequestViewHolder(View itemView) {
super(itemView);
myView = itemView;
}
public void setTrans(String profile){
TextView trans = (TextView) myView.findViewById(R.id.transaction);
trans.setText(profile);
}
public void setRequestDeadline(String dead){
TextView rdead = (TextView) myView.findViewById(R.id.rDead);
rdead.setText(dead);
}
public void setRequestDescription(String desc){
TextView rdesc = (TextView) myView.findViewById(R.id.rDesc);
rdesc.setText(desc);
}
public void setDateTimeAccepted(String date){
TextView dta = (TextView) myView.findViewById(R.id.rAccept);
dta.setText(date);
}
public void setRequestLocation(String loc){
TextView rloc = (TextView) myView.findViewById(R.id.rLoc);
rloc.setText(loc);
}
public void setProfile(Context c, String profile){
ImageView rprofile = (ImageView) myView.findViewById(R.id.HPicture);
Picasso.with(c).load(profile).into(rprofile);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
I haven't really tried anything because the other questions I've seen here so far doesn't seem to be similar to my codes.
You will have to use an existing library / widget unless you want to create the functionality from scratch.
For instance:
https://android-arsenal.com/details/1/4897
You have full instructions there but basically:
mRecyclerView = new CdsRecyclerView(this);
mRecyclerView = (CdsRecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// Adapter:
mRecyclerViewAdapter = new RecyclerViewAdapter(this, getData());
mRecyclerView.setAdapter(mRecyclerViewAdapter);
// Enable swipe:
mRecyclerView.enableItemSwipe();
// Listener:
mRecyclerView.setItemSwipeCompleteListener(new CdsItemTouchCallback.ItemSwipeCompleteListener() {
#Override
public void onItemSwipeComplete(int position) {
Toast.makeText(MainActivity.this, "Item was swiped:" + position,
Toast.LENGTH_SHORT).show();
}
});

How to notify the data is change from sqlite to recycler view?

I have a application that contain RecyclerView and FragmentDialog , and I get data from user to sqlite and all is working ,
but the problem is when i add data to sql and display it in RecyclerView i have to restart the app to show the data , how can i notify that data is changed ???
This is my DialogFragment
public class addAction extends DialogFragment implements View.OnClickListener {
EditText addTitle, addDesc;
Button add, clear,close;
private DatabaseHelpher db;
String Title,Des;
public addAction() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addaction, container, false);
addTitle = (EditText) rootView.findViewById(R.id.todotitle);
addDesc = (EditText) rootView.findViewById(R.id.tododescription);
add = (Button) rootView.findViewById(R.id.addbutton);
add.setOnClickListener(this);
close = (Button) rootView.findViewById(R.id.Close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
clear = (Button) rootView.findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addTitle.setText("");
addDesc.setText("");
}
});
return rootView;
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getDialog().setTitle("Add Action");
db = new DatabaseHelpher(getContext());
}
private void insert() {
Title = addTitle.getText().toString();
Des= addDesc.getText().toString();
db.insertIntoDB(Title, Des);
}
#Override
public void onClick(View v) {
if (addTitle.getText().toString().trim().equals("")) {
addTitle.setError(" Title is required!");
} else if (addDesc.getText().toString().trim().equals("")) {
addDesc.setError(" Postion is required!");
}
Toast.makeText(getContext(),"your data is saved", Toast.LENGTH_SHORT).show();
insert();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
List<ToDoModule> dbList;
RecyclerView mRecyclerView;
DatabaseHelpher helpher;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<ToDoModule>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.AppRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(this,dbList);
this.dbList =helpher.getDataFromDB();
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_action_name);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
addAction add = new addAction();
add.show(fm,"fragment_edit_name");
}
});
}
#Override
protected void onResume() {
super.onResume();
}
}
getdata() method from SQlHelper
public List<ToDoModule> getDataFromDB(){
List<ToDoModule> modelList = new ArrayList<ToDoModule>();
String query = "select * from "+ TODO_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
ToDoModule model = new ToDoModule();
model.setActionTitle(cursor.getString(1));
model.setActionDesc(cursor.getString(2));
modelList.add(model);
}while (cursor.moveToNext());
}
return modelList;
}
RecyclerViewAdapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<ToDoModule> dbList;
static Context context;
RecyclerAdapter(Context context, List<ToDoModule> dbList ){
this.dbList = new ArrayList<ToDoModule>();
this.context = context;
this.dbList = dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.actionitems, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.Title.setText(dbList.get(position).getActionTitle());
holder.Desc.setText(dbList.get(position).getActionDesc());
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView Title,Desc;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
Title = (TextView) itemLayoutView.findViewById(R.id.todotitle);
Desc = (TextView)itemLayoutView.findViewById(R.id.des);
}
}
}
You need to create a function in MainActivity to update data of in recycler view. Then call that function from dialog fragment.
In MainActivity
public void updateData(){
dbList =helpher.getDataFromDB();
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
}
And in dialog fragment you can do same thing using interface or casting activity instance to MainActivity
((MainActivity) grtActivity()).updateData();
Or do it using an interface.
The problem is in these 2 lines.
mAdapter = new RecyclerAdapter(this,dbList);
this.dbList =helpher.getDataFromDB();
First you set a reference of dbList to the adapter and then you change the refernece of the list to a list you create in getDataFromDB() and the list in the adapter stays the old one with no items.
in order to fix that change the second line of this code to
this.dbList.addAll(helpder.getDataFromDB());
and than make sure you call adapter.notifyDataSetChanged()
EDIT: Nevermind it seems you call the db before that anyway.
Are you sure there are items in the db?

Data from backend not showing up in recyclerview

I am trying to get data that I put into a Backendless console and show it in my android application but the data is not showing up. It just shows a blank activity/screen. It's not crashing either. Frankly, I'd be more pleased if it was. Any help would be greatly appreciated!
Heres my code:
private List<Cake> list;
private Context context;
public CakeAdapter(Context context, List<Cake> list) {
this.context = context;
this.list = list;
}
#Override
public CakeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cake, parent, false);
return new CakeHolder(view);
}
#Override
public void onBindViewHolder(CakeHolder holder, int position) {
final Cake cake = list.get(position);
holder.type.setText(cake.getType());
holder.description.setText(cake.getDescription());
// holder.type.setText("I dont know.");
// holder.description.setText("Just some random text. I am in the mood for pizza.");
}
#Override
public int getItemCount() {
return list.size();
}
public class CakeHolder extends RecyclerView.ViewHolder {
//Setup Views
CardView card;
TextView type;
TextView description;
public CakeHolder(View itemView) {
super(itemView);
//Assign views by ID
card = (CardView) itemView.findViewById(R.id.cakecard);
type = (TextView) itemView.findViewById(R.id.type);
description = (TextView) itemView.findViewById(R.id.description);
}
}
}
public class CakeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, FloatingActionButton.OnClickListener {
//Setup Views
private Toolbar toolbar;
private SwipeRefreshLayout swipe;
private FloatingActionButton fab;
private RecyclerView recycler;
//Setup adapter
private CakeAdapter adapter;
//Setup Cake
private List<Cake> Cake = new ArrayList<>();
//Setup backend call
private BackendlessCollection<Cake> cakes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Cake);
//Setup toolbar
toolbar = (Toolbar) findViewById(R.id.bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//Setup SwipeView
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(this);
swipe.setColorSchemeResources(R.color.colorPrimaryDark,
R.color.blade,
android.R.color.holo_orange_light,
R.color.fruit);
//Setup Recyclerview
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setLayoutManager(new LinearLayoutManager(this));
recycler.setHasFixedSize(true);
adapter = new CakeAdapter(this, cake);
recycler.setAdapter(adapter);
//Setup FAB and attach to recycler
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.attachToRecyclerView(recycler);
fab.setOnClickListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
supportFinishAfterTransition();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
//do something later
}
#Override
public void onRefresh() {
refreshCakes();
if (swipe.isRefreshing()) {
swipe.setRefreshing(false);
}
}
private void refreshCakes() {
QueryOptions query = new QueryOptions();
query.setPageSize(20);
BackendlessDataQuery queries = new BackendlessDataQuery(query);
Backendless.Data.of(Cake.class).find(queries, new AsyncCallback<BackendlessCollection<Cake>>() {
#Override
public void handleResponse(BackendlessCollection<Cake> cakeBackendlessCollection) {
cakes = cakeBackendlessCollection;
addMore(cakeBackendlessCollection);
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
Log.d("Cake", "Error: " + backendlessFault.getMessage());
}
});
}
private void addMore(BackendlessCollection<Cake> next) {
cake.addAll(next.getCurrentPage());
adapter.notifyDataSetChanged();
}
}
Well, I'm gonna duplicate an answer from the support topic: the name of the table on Backendless should match exactly the name of your class.
Or otherwise, you must call Backendless.Data.mapTableToClass("YourTableName", YourClassName.class) somewhere at the start of your program.

Categories

Resources