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

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?

Related

Adding item dynamically to recyclerview

I am building a notepad app. I am trying to add another item to the recyclerview as soon as the new note is saved by the user.
public class NotePad extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_pad);
final FloatingActionButton button =
(FloatingActionButton)findViewById(R.id.save_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveData();
}
});
}
// To Send Note Title to MainActivity
public void SendData() {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
Log.d("Check","str:"+str);
Intent intent = new Intent(NotePad.this,MainActivity.class);
intent.putExtra(EXTRA_MESSAGE, str);
startActivity(intent);
}
// To Save Note Content
public void SaveData() {
FileOutputStream outputStream;
try {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
String content = findViewById(R.id.textView).toString();
Log.d("Test","inside try block");
outputStream = openFileOutput(str, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
Log.d("Test","save done");
SendData();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am saving a note and sending the title(str) that is to be displayed in recyclerview row to MainActivity as shown above.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<String> notes = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String title = intent.getStringExtra(NotePad.EXTRA_MESSAGE);
Log.d("Check","title added"+title);
notes.add(title);
BuildRecyclerView();
}
public void BuildRecyclerView() {
recyclerView = (RecyclerView)findViewById(R.id.recycle_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(notes);
recyclerView.setAdapter(mAdapter);
}
But whenever I add a new note it overwrites the first entry in the recyclerview instead of occupying the next row of the recyclerview. This is my adapter code:
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<String> Notes_list = new ArrayList<String>();
public MyAdapter(ArrayList<String> notes) {
Notes_list = notes;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_items,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int
position) {
holder.mTextView.setText(Notes_list.get(position));
}
#Override
public int getItemCount() {
return Notes_list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.view_holder);
}
}
}
Because you pass last item to MainActivity and generate a new RecyclerView with passed item. You have to keep notes array on first class and pass whole array to MainActivity with intent.

How can i get the all value of Recyclerview on Button click?

public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}
Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.
Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});

Android - FirebaseUI sometimes not showing RecyclerView

I have a fragment called HomeFragment inside an activity called MainActivity that using RecyclerView to load the data from Firebase. And when I clicked the RecyclerView, it will open a new activity called ItemActivity.
The problem is sometimes the RecyclerView does not load anything when it opened the new activity.
For example, I clicked the RecyclerView in the HomeFragment, the new ItemActivity will start but without any RecyclerView, and after I closed it and reopen it again, the RecyclerView is showing. This happened on a random occasion, sometimes it loads and sometimes it does not load the RecyclerView.
And whenever I put adapter.stopListening(), the RecyclerView never show up in the ItemActivity.
HomeFragment
public class HomeFragment extends Fragment {
private OnFragmentInteractionListener mListener;
FirebaseDatabase database;
DatabaseReference category;
FirebaseRecyclerAdapter adapter;
TextView txtUsername;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container,false);
// set name for user
String username = Common.currentUser.getEmail();
StringTokenizer tokens = new StringTokenizer(username, "#");
String first = tokens.nextToken();// this will contain string before #
// set name for user
txtUsername = (TextView) view.findViewById(R.id.textUsername);
txtUsername.setText(first);
// load category
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewCategory);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
loadMenu();
return view;
}
private void loadMenu(){
Query query = FirebaseDatabase
.getInstance()
.getReference()
.child("Category");
FirebaseRecyclerOptions<Category> options =
new FirebaseRecyclerOptions.Builder<Category>()
.setQuery(query, Category.class)
.build();
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(options) {
#Override
public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity())
.inflate(R.layout.category_item, parent, false);
return new CategoryViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull CategoryViewHolder holder, int position, #NonNull Category model) {
holder.txtMenuName.setText(model.getName());
Picasso.with(getActivity()).load(model.getImage())
.into(holder.imageView);
final Category clickItem = model;
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
// get category id and send to new activity
Intent intent = new Intent(getActivity(), ItemActivity.class);
// get category id to filter
intent.putExtra("CategoryId",adapter.getRef(position).getKey());
startActivity(intent);
}
});
}
};
recyclerView.setAdapter(adapter);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onStop() {
super.onStop();
//adapter.stopListening();
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
//Toast.makeText(context, "Home Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
ItemActivity
public class ItemActivity extends AppCompatActivity {
ImageView imageView;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference itemList;
String categoryId;
public FirebaseRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Firebase
database= FirebaseDatabase.getInstance();
itemList = database.getReference("Item");
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewItem);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// get intent
if (getIntent() != null) {
categoryId = getIntent().getStringExtra("CategoryId");
}
if(!categoryId.isEmpty() && categoryId != null) {
loadListItem(categoryId);
}
}
private void loadListItem(String categoryId) {
Query query = itemList.orderByChild("CategoryId").equalTo(categoryId);
FirebaseRecyclerOptions<Item> options =
new FirebaseRecyclerOptions.Builder<Item>()
.setQuery(query, Item.class)
.build();
adapter = new FirebaseRecyclerAdapter<Item, ItemViewHolder>(options) {
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_item, parent, false);
return new ItemViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ItemViewHolder holder, int position, #NonNull Item model) {
holder.itemTitle.setText(model.getName());
holder.itemUsername.setText(model.getUsername());
holder.itemPrice.setText(model.getPrice());
holder.itemDescription.setText(model.getDescription());
holder.itemPhone.setText(model.getPhone());
holder.itemDate.setText(model.getDate());
holder.itemQuality.setText(model.getQuality());
Picasso.with(getBaseContext()).load(model.getPicture())
.into(holder.itemImage);
final Item clickItem = model;
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//
}
});
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
Toast.makeText(this, "" + categoryId, Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
//adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
//adapter.stopListening();
}
I found the problem.
Just remove recyclerView.setHasFixedSize(true);

display data into recycler view from sqlite without restart the app

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 click into add into Dialog, I have to restart the application to display the data , how I can display the data without Restart?
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 can implement notification to the adapter when the data gets changed.
Ideally the adapter RecyclerAdapter, will be intimated using the following methods.
1) notifyItemRemoved
2) notifyItemRangeChanged
3) notifyItemRangeInserted
there are other methods available , which can be found in this API reference link
Now inorder to update the data, use recyclerAdapterObject.notifyDataSetChanged();
Go through this reference link more more detailed implementation under section Notifying the Adapter
At first don't do this in your RecyclerAdapter:
RecyclerAdapter(Context context, List<ToDoModule> dbList ){
this.dbList = new ArrayList<ToDoModule>();
this.context = context;
this.dbList = dbList;
}
You shouldn't save Context unless you really understand why you need this. Here you don't use it at all. Also the this.dbList = new ArrayList<ToDoModule>() is not necessary since you do this.dbList = dbList anyway.
You can add an interface to your addAction dialog fragment like
public class addAction extends DialogFragment implements View.OnClickListener {
public interface OnToDoAddedListener{
void onTodoAdded();
}
private OnToDoAddedListener mToDoAddedListener;
...
public setOnTodoAddedListener(OnToDoAddedListner listener){
this.mToDoAddedListener = listener;
}
}
and then call the mToDoAddedListener.onTodoAdded() in your insert() method.
Then you should add a listener in your MainActivity.onCreate method to the addAction object and call this code on your onTodoAdded() implementation:
this.dbList.clear();
this.dbList.addAll(helpher.getDataFromDB();
mAdapter.notifyDataSetChanged();
In your code i'm not seeing where you update the list (Just the button with an add action) so i will explain with a generic example.
Where you instantiate your RecyclerAdapter:
final List<ObjectXPTO> list = new ArrayList<>();
list =helpher.getDataFromDB();
final RecyclerAdapter mAdapter = new RecyclerAdapter(this,list);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ObjectXPTO newObject = new ObjectXPTO(); // Just to exemplify, you need to get this object from you database
list.add(newObject);
mAdapter.notifyDataSetChanged();
}
});
Resuming, you need to add the new object in the list you used on your adapter and notify the adapter that the data set is changed, so the adapter will update
Edit:
If i understand correctly you add the data on your fragment or somewhere out of your Activity, so you need to pass to Activity (where the adapter is) the information that the data changed.
Add this method to MainActivity :
public static void updateList(List<ToDoModule> newList){
dbList.clear();
dbList.addAll(newList);
mAdapter.notifyDataSetChanged();
}
So in the fragment, you can pass the new List and update the list in MainActivity, or you can do a new query inside this method.
This is just for explaining, you may need to compare (outside the UI thread) if an item is not in the list and only add the items that are not already inside (to avoid the whole list to get updated).
Ps. You you need to change the list and adapter variables to static.

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