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.
Related
I'm trying to show any pictures with Staggered Grid, but many problems are occuring.
Firstly, when I pulled up to the top, it moves items for example from left to right, or swap the column of left and right.
See below .gif:
I have searched for a solution to this problem via Google already. I am using the this code in my project:
StaggeredGridLayoutManager Layoutmanager = new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL);
manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(manager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
((StaggeredGridLayoutManager)recyclerView.getLayoutManager()).invalidateSpanAssignments();
}
});
Unfortunately, there is still a serious problem occurring when I scroll up. The item still moves and it will scrolls far though even if I just scroll shortly.
See below .gif:
How can I deal with these problems, or otherwise achieve this effect?
MainActivity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private photos[] photoses = {
new photos("Tags:",R.drawable.timg),
new photos("Tags:",R.drawable.timg1),
new photos("Tags:",R.drawable.timg2),
new photos("Tags:",R.drawable.timg3),
new photos("Tags:",R.drawable.timg4),
new photos("Tags:",R.drawable.timg5),
new photos("Tags:",R.drawable.timg6),
new photos("Tags:",R.drawable.timg7),
new photos("Tags:",R.drawable.timg8),
new photos("Tags:",R.drawable.timg9),
new photos("Tags:",R.drawable.timg10),
new photos("Tags:",R.drawable.timg11),
new photos("Tags:",R.drawable.timg12),
};
private List<photos> photosList = new ArrayList<>();
private photoAdapter adapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.edit_bar:
Toast.makeText(this,"edit",Toast.LENGTH_SHORT).show();
break;
case R.id.search_bar:
Toast.makeText(this,"search",Toast.LENGTH_SHORT).show();
break;
default:break;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBar actionBar = getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.homemenu);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view,"Hello World",Snackbar.LENGTH_SHORT).show();
}
});
initPhotos();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
adapter = new photoAdapter(photosList);
recyclerView.setAdapter(adapter);
}
private void initPhotos() {
photosList.clear();
for (int i = 0;i<100;i++){
Random random = new Random();
int index = random.nextInt(photoses.length);
photosList.add(photoses[index]);
}
}
}
photoAdapter:
public class photoAdapter extends RecyclerView.Adapter<photoAdapter.ViewHolder> {
private Context mcontext;
private List<Integer> mHeights;
private List<photos> mPhotoList;
static class ViewHolder extends RecyclerView.ViewHolder{
CardView cardView;
ImageView photoView;
TextView photoTag;
public ViewHolder(View view){
super(view);
cardView = (CardView) view;
photoView = (ImageView) view.findViewById(R.id.photo_view);
photoTag = (TextView) view.findViewById(R.id.photo_tag);
}
}
public photoAdapter(List<photos> photoList){
mPhotoList = photoList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mcontext==null){
mcontext = parent.getContext();
}
View view = LayoutInflater.from(mcontext).inflate(R.layout.photo_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
photos photo = mPhotoList.get(position);
holder.photoTag.setText(photo.getTag());
Glide.with(mcontext).load(photo.getImageId()).into(holder.photoView);
}
#Override
public int getItemCount() {
return mPhotoList.size();
}
}
From the Android docs
Staggered grids are likely to have gaps at the edges of the layout. To
avoid these gaps, StaggeredGridLayoutManager can offset spans
independently or move items between spans. You can control this
behavior via setGapStrategy(int)
Reference:
https://developer.android.com/reference/android/support/v7/widget/StaggeredGridLayoutManager.html
https://stackoverflow.com/a/34274327/3701433
I have implement Realm database in my App. At first I want to show some prelod data. Till now I have only three data here. I have implement a dialog fragment which I used to add data in Realm database. I have read the official documentation of Realm. But the implementation of Adapter class is so complecated for me. Hence I have used RecyclerView.Adapter in my Adpater class. Now the problem I am facing that After adding the information the data is not showing promptly.The data is not upadted quickly. it is showing after clicking the add button again. I cannot identify what would be the problem in this case. Also I am happy if someone provide me suggessstion if the writing of this code is not good. Sorry for my bad English.
Edited Adapter Class
Here is my Adpater class
public class PersonAdapter extends RealmRecyclerViewAdapter<PersonModel, PersonAdapter.PersonHolder> {
private RealmResults<PersoneModel> realmResults;
private List<PersonModel> personModels;
private Context context;
public interface PersonListListener {
void addPerson(PersonModel personModel);
void editPerson(PersonModel personModel);
}
public PersonAdapter(Context context,RealmResults<PersonModel> realmResults) {
this.realmResults = realmResults;
this.context = context;
}
// create new views (invoked by the layout manager)
#Override
public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// inflate a new person view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false);
return new PersonHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
// get the colleague
final PersonModel person=realmResults.get(position);
// cast the generic view holder to the specific one
final PersonHolder holder = (PersonHolder) viewHolder;
holder.name.setText(person.getName());
holder.companye.setText(person.getCompany());
holder.title.setText(person.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//editDataInterface.editData(view,position);
int pos = (int)view.getTag();
Intent i=new Intent(context,DetailPerson.class);
i.putExtra("name",person.getName());
i.putExtra("company",person.getCompany());
i.putExtra("title",person.getTitle());
context.startActivity(i);
}
});
}
// return the size of your data set (invoked by the layout manager)
public int getItemCount() {
return realmResults.size();
}
public class PersonHolder extends RecyclerView.ViewHolder{
public CardView cardView;
public ImageView picture;
public TextView name;
public TextView company;
public TextView title;
public ColleagueHolder(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.person_name);
company=(TextView) itemView.findViewById(R.id.company_name);
title=(TextView) itemView.findViewById(R.id.job_title);
cardView=(CardView)itemView.findViewById(R.id.cardview_user);
}
}
}
Edited Activity Calss My Activity class is
public class MainActivity extends AppCompatActivity implements PersonAdapter.PersonListListener{
private RecyclerView recyclerView;
private PersonAdapter adapter;
private Realm personRealm;
private List<PersonModel> personObject;
private RealmResults<PersonModel> dataResult;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
personRealm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.person_recycler);
setUpRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
showAllPersons();
}
private void showAllPersons() {
dataResult = personRealm.where(PersonModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}
private void setAdapter(RealmResults<PersonModel> results) {
adapter = new PersonAdapter(this, results);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void setUpRecycler() {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true);
// use a linear layout manager since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
}
private void setRealmData(){
List<MyColleagueModel> colleague = new ArrayList<>();
MyColleagueModel model = new MyColleagueModel();
model.setId(1 + System.currentTimeMillis());
model.setName("Name1");
model.setCompany("Comapny1");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(2 + System.currentTimeMillis());
model.setName("Name2");
model.setCompany("Comapny2");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(3 + System.currentTimeMillis());
model.setName("Name3");
model.setCompany("Comapny3");
model.setTitle("Title3");
colleague.add(model);
for (MyColleagueModel realmModel : colleague) {
// Persist the colleague data
colleagueRealm.beginTransaction();
colleagueRealm.copyToRealm(realmModel);
colleagueRealm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recycler_menu, menu);
final MenuItem item = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
//onOptionsItemSelected(MenuItem item) add will open dialog box, which allows user to fill required data
if (id == R.id.addColleague) {
showAlertDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showAlertDialog() {
EditColleagueFragment dialog = new EditColleagueFragment();
//dialog.setPositiveButtonClickListener(this);
dialog.show(getSupportFragmentManager(), DIALOG_TAG);
//adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (colleagueRealm!= null)
colleagueRealm.close();
super.onDestroy();
}
/*#Override
public void onSaved() {
dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}*/
#Override
public void addPerson(MyColleagueModel colleagueModel) {
}
#Override
public void editPerson(MyColleagueModel colleagueModel) {
}
}
Using realm-android-adapters:
dependencies {
compile 'io.realm:android-adapters:2.1.0'
}
You need to do
public class MyColleaguesAdapter extends RealmRecyclerViewAdapter<MyColleagueModel, MyColleaguesAdapter.ColleagueHolder> {
public interface ColleagueListListener {
void addPerson(MyColleagueModel colleagueModel);
void editPerson(MyColleagueModel colleagueModel);
}
private final ColleagueListListener colleagueListListener;
public MyColleaguesAdapter(ColleagueListListener colleagueListListener, RealmResults<MyColleagueModel> results) {
super(results, true);
this.colleagueListListener = colleagueListListener;
}
#Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ColleagueHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false));
}
#Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
final MyColleagueModel myColleague = getData().get(position);
holder.bind(myColleague);
}
public class ColleagueHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public ImageView colleaguePicture;
public TextView colleagueName;
public TextView companyName;
public TextView jobTitle;
private MyColleagueModel myColleague;
private final View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
colleagueListListener.editPerson(myColleague);
}
}
public ColleagueHolder(View itemView) {
super(itemView);
//colleaguePicture=(ImageView)itemView.findViewById(R.drawable.profile_image);
colleagueName=(TextView)itemView.findViewById(R.id.colleague_name);
companyName=(TextView) itemView.findViewById(R.id.company_name);
jobTitle=(TextView) itemView.findViewById(R.id.job_title);
cardView=(CardView)itemView.findViewById(R.id.cardview_user);
}
}
public void bind(MyColleagueModel myColleague) {
this.myColleague = myColleague;
holder.colleagueName.setText(myColleague.getName());
holder.companyName.setText(myColleague.getCompany());
holder.jobTitle.setText(myColleague.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(listener);
}
}
and
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
private Realm realm;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
realm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyColleaguesAdapter(this, realm.where(MyColleagueModel.class).findAllSortedAsync("id"));
recyclerView.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
realm = null;
}
}
Step 1:
Inside EditColleagueFragment create interface
public interface onSaveClickListener {
void onSaved()
}
private onSaveClickListener mSaveClickListener;
public void setPositiveButtonClickListener(onSaveClickListener listener){
mSaveClickListener=listener;
}
Step 2: Inside MyColleaguesPage
implement onSaveClickListener
#Override
void onSaved(){
dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}
private void showAlertDialog() {
EditColleagueFragment dialog = new EditColleagueFragment();
dialog.setPositiveButtonClickListener(this)
dialog.show(getSupportFragmentManager(), DIALOG_TAG);
}
Step 3 :
inside
void savePerson(){
-----
---
mSaveClickListener.onSaved();
}
I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);
I want to animate the recyclerview so the items are added in a sequence (sliding from right to left), I mean, the first item starts sliding then when it's around the middle of the screen, the second item starts sliding and so on.
I tried adding this library (https://github.com/wasabeef/recyclerview-animators) but I'm not sure if I made something wrong or if it doesn't work like this.
Any ideas?
Activity
private ArrayList<OptionListItem> mOptionsList = new ArrayList<>();
private RecyclerView mRecyclerView;
private OptionListAdapter mListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mListAdapter = new OptionListAdapter(mOptionsList);
mRecyclerView = (RecyclerView) findViewById(R.id.options_list);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mListAdapter);
mRecyclerView.setItemAnimator(new SlideInLeftAnimator());
addOptionsToList();
}
private void addOptionsToList() {
OptionListItem listItem = new OptionListItem(
ScanActivity.class,
"Controle",
"Efetue o bloqueio/desbloqueio",
R.drawable.ic_lock,
R.drawable.colored_bar_bg1
);
mListAdapter.add(listItem);
listItem = new OptionListItem(
ScanActivity.class,
"Opção 2",
"Descrição da opção 2",
R.drawable.ic_car,
R.drawable.colored_bar_bg2
);
mListAdapter.add(listItem);
listItem = new OptionListItem(
ScanActivity.class,
"Opção 3",
"Descrição da opção 3",
R.drawable.ic_lightbulb,
R.drawable.colored_bar_bg4
);
mListAdapter.add(listItem);
}
Adapter
public class OptionListAdapter extends RecyclerView.Adapter<OptionListAdapter.OptionListItemHolder> {
private final ArrayList<OptionListItem> optionList;
public OptionListAdapter(ArrayList<OptionListItem> optionList) {
this.optionList = optionList;
}
#Override
public OptionListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = LayoutInflater.from(parent.getContext())
.inflate(R.layout.options_list_item_layout, parent, false);
return new OptionListItemHolder(item);
}
#Override
public void onBindViewHolder(OptionListItemHolder holder, int position) {
OptionListItem item = optionList.get(position);
holder.cardTitle.setText(item.getTitle());
holder.cardSubtitle.setText(item.getSubtitle());
holder.icon.setImageResource(item.getIcon());
holder.coloredBar.setBackgroundResource(item.getBar());
holder.activity = item.getActivity();
}
public void add(OptionListItem item) {
int position = getItemCount();
this.optionList.add(position, item);
notifyItemInserted(position);
}
#Override
public int getItemCount() {
return optionList.size();
}
public class OptionListItemHolder extends RecyclerView.ViewHolder {
private TextView cardTitle;
private TextView cardSubtitle;
private ImageView icon;
private View coloredBar;
private View optionBackground;
private Class<?> activity;
public OptionListItemHolder(View v) {
super(v);
cardTitle = (TextView)v.findViewById(R.id.card_title);
cardSubtitle = (TextView)v.findViewById(R.id.card_subtitle);
icon = (ImageView)v.findViewById(R.id.icon);
coloredBar = v.findViewById(R.id.colored_bar);
optionBackground = v.findViewById(R.id.option_background_container);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), activity);
view.getContext().startActivity(intent);
}
});
}
}
}
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?