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.
Related
Can't figure out how to delete specific item from recycler view and realm database.
I figured out to delete item from recycler view so when I when click on button delete, it deletes that item, but can't figure out how to delete from datebase as well becouse of course when I restart app, same date appears becouse it's not deleted from database.
listitem.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/parentLayout">
<TextView
android:id="#+id/tv_task"
android:text="TASK1"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"/>
<Button
android:id="#+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_alignParentRight="true"/>
</RelativeLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayList<String> mTasks = new ArrayList<>();
EditText et_newtask;
Button btn_add;
Realm realm;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//SETUP RV
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//SETUP REALM
realm = Realm.getDefaultInstance();
RealmHelper helper = new RealmHelper(realm);
mTasks = helper.retrive();
//BIND
adapter = new RecyclerViewAdapter( mTasks,this);
recyclerView.setAdapter(adapter);
initTextViewTasks();
}
private void initTextViewTasks(){
et_newtask = (EditText) findViewById(R.id.et_newTask);
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
Tasks t = new Tasks();
String value = et_newtask.getText().toString();
t.setTasks(value);
//SAVE DATA to DB
RealmHelper helper = new RealmHelper(realm);
helper.save(t);
et_newtask.setText("");
//refresh DB
mTasks = helper.retrive();
adapter = new RecyclerViewAdapter(mTasks,MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
}
}
Tasks class:
public class Tasks extends RealmObject {
private String tasks;
public String getTasks() {
return tasks;
}
public void setTasks(String tasks) {
this.tasks = tasks;
}
}
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private ArrayList<String> mTv_tasks = new ArrayList<>();
private ArrayList<Tasks> dataList = new ArrayList<>();
private Context mContext;
OnClickInterface onClickInterface;
Realm realm;
public RecyclerViewAdapter(ArrayList<String> mTv_tasks,OnClickInterface onClickInterface, Context mContext) {
this.mTv_tasks = mTv_tasks;
this.mContext = mContext;
this.onClickInterface = onClickInterface;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_listitem, viewGroup,false);
ViewHolder viewHolder = new ViewHolder(view,onClickInterface);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int position) {
viewHolder.tv_task.setText(mTv_tasks.get(position));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, mTv_tasks.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mTv_tasks.size();
}
When I click on specific btn_delete I want to delete that specific object (row) of recycler view.
I'm assuming that you know how to delete an item from Realm, but you don't know how to do that with an onclicklistener inside your adapter.
1) Create an interface to do the communication between adapter and activity
public interface OnClickInterface {
void onDeleteClicked(int id); //user id, or whatever you need to know what item you should delete
}
2) Receive your listener in the adapter constructor
public class YourAdapter ... {
OnClickInterface onClickInterface;
//initialilize in a constructor
public Adapter(OnClickInterface onClickInterface){
this.onClickInterface = onClickInterface
}
}
3) Call the listener inside your onClick to delete the item from RecyclerView
public void onClick(View v) {
if(v.equals(btn_delete)){
this.onClickInterface.onDeleteClicked(id)
(...) remove from recycler view
}
}
4) Implements OnCickInterface on your Activity
public class MainActivity extends AppCompatActivity implements OnClickInterface {
#Override
public void onDeleteClicked(int id){
//delete from realm
}
}
Thats it, really hope that this helps with your problem
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);
}
});
I've been struggling with this issue for a while. I have an activity (SerieActivity) where I allow the user to select various items and give them values. The items are stored in an ArrayList<Variable>, where Variable is a class that I've defined. The items are displayed in a RecyclerView. This works just fine. Upon clicking a button in that activity, the user is sent to another activity (Result) that displays the exact same items from the ArrayList in SerieActivity, with the respective values that the user has input.
In my Result activity I have created an instance of the SerieActivity class and then made an ArrayList to store the values of the original ArrayList from SerieActivity. However it seems like the RecyclerView from my Result class doesn't get populated with data. What could be going wrong?
Here's my code:
Variable class
public class Variable {
boolean known;
String unit, name;
double value;
}
RVAdapterSerie - the adapter for the RecyclerView used in the SerieActivity class
public class RVAdapterSerie extends RecyclerView.Adapter<RVAdapterSerie.ViewHolder> {
private Context context;
private ArrayList<Variable> variableList;
public RVAdapterSerie(Context context, ArrayList<Variable> variableList) {
this.context = context;
this.variableList = variableList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RVAdapterSerie.ViewHolder holder, int position) {
Variable v = variableList.get(position);
holder.setItems(v);
}
#Override
public int getItemCount() {
return variableList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CheckBox checkBox;
private EditText editText;
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.value_cb);
editText = itemView.findViewById(R.id.value_et);
textView = itemView.findViewById(R.id.value_tv);
}
public void setItems (Variable variable) {
checkBox.setText(variable.getName());
editText.setText(String.format("%.3f", variable.getValue()));
textView.setText(variable.getUnit());
}
}
}
SerieActivity class
public class SerieActivity extends AppCompatActivity {
public ArrayList<Variable> mList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_serie);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerView recyclerView = findViewById(R.id.serie_rv);
RVAdapterSerie rvAdapterSerie = new RVAdapterSerie(this, mList);
recyclerView.setAdapter(rvAdapterSerie);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
populateList();
rvAdapterSerie.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.serie_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SerieActivity.this, Result.class);
intent.putExtra("tag", "serie");
startActivity(intent);
}
});
}
public void populateList() {
mList.add(new Variable(false, "dummyunit", "dummyname", 0));
mList.add(new Variable(false, "diofishafuio", "ghfuef", 0));
mList.add(new Variable(false, "diofishdfesffafuio", "ghfuef", 0));
//add dummy items
}
}
RVResultAdapter - adapter for the RecyclerView in Result class
public class RVResultAdapter extends RecyclerView.Adapter<RVResultAdapter.ViewHolder> {
private Context context;
private ArrayList<Variable> variableList;
public RVResultAdapter(Context context, ArrayList<Variable> variableList) {
this.context = context;
this.variableList = variableList;
}
#Override
public RVResultAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.result_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RVResultAdapter.ViewHolder holder, int position) {
Variable v = variableList.get(position);
holder.setItems(v);
}
#Override
public int getItemCount() {
return variableList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
public ViewHolder(View itemView) {
super(itemView);
textView1 = itemView.findViewById(R.id.result_name_tv);
textView2 = itemView.findViewById(R.id.result_value_tv);
textView3 = itemView.findViewById(R.id.result_unit_tv);
}
public void setItems (Variable variable) {
textView1.setText(variable.getName());
textView2.setText(String.format("%.3f", variable.getValue()));
textView3.setText(variable.getUnit());
}
}
}
Result class
public class Result extends AppCompatActivity {
public ArrayList<Variable> rList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Intent intent = getIntent();
String tag = intent.getExtras().getString("tag");
if (tag.equals("serie")) {
SerieActivity serieActivity = new SerieActivity();
rList = serieActivity.mList;
}
RecyclerView recyclerView = findViewById(R.id.result_rv);
RVResultAdapter rvResultAdapter = new RVResultAdapter(this, rList);
recyclerView.setAdapter(rvResultAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
rvResultAdapter.notifyDataSetChanged();
}
}
My problem is with the RecyclerView in Result. It shows the blue "end of content" things when I scroll up and down, so I guess the RecyclerView is there, but doesn't get any data. Any help is greatly appreciated. I am quite new to Android and Java programming, so I guess it must be a dumb thing that I just don't see.
What are you doing dude. How can you get list from a new object of SerieActivity.class?
if (tag.equals("serie")) {
SerieActivity serieActivity = new SerieActivity();
rList = serieActivity.mList;
}
This is totally wrong way. If you want to pass list between activities. You can use parcelable methods putExtra and getExtra.
Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)
Here is a skeleton of the code you need:
First you need to create a Parcelable object class, see the example
public class Student implements Parcelable {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int arg1) {
// TODO Auto-generated method stub
dest.writeInt(id);
dest.writeString(name);
}
public Student(Parcel in) {
id = in.readInt();
name = in.readString();
}
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
And the list
ArrayList<Student> arraylist = new ArrayList<Student>();
Code from Calling activity
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);
this.startActivity(intent);
Code on called activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}
So you calling SerieActivity constructor in Results activity and execute populateList() inside onCreate(). You shouldn't create activities in this way because onCreate() will be never called. Instead of this you should pass data using putExtra and use Parcelable interface.
just set the recyclerview code like this first initialize adapter then set layout manager and then set to adapter to recyclerview.
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new MoviesAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
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?
I just started using RecyclerViews but i cant completely understand how to add or remove items from it. Below i will attach my adapter code it is a test code and everything in the layout works fine. I feel like im also writing too much unnecessary code so any tips or criticism is appreciated.
public class PlatesAdapter extends
RecyclerView.Adapter<PlatesAdapter.ViewHolder> {
//Declaring a List<> of Plates
private List<Plates> mPlates;
int amountOfPlates;
public static class ViewHolder extends RecyclerView.ViewHolder {
//Declaring Buttons and textViews
public TextView plateWeightTextView, amountOfPlatesTextView;
public Button addButton, subButton, addLayoutButton;
public ViewHolder(View itemView) {
super(itemView);
//initializing Buttons and TextViews
plateWeightTextView = (TextView) itemView.findViewById(R.id.plate_weight_value_textView);
amountOfPlatesTextView = (TextView) itemView.findViewById(R.id.amount_of_plates_textView);
addButton = (Button) itemView.findViewById(R.id.add_button);
subButton = (Button) itemView.findViewById(R.id.subtract_button);
addLayoutButton = (Button) itemView.findViewById(R.id.button);
}
}
//Constructor
public PlatesAdapter(List<Plates> plates) {
mPlates = plates;
}
#Override
public PlatesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View PlatesView = inflater.inflate(R.layout.plate_item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(PlatesView);
return viewHolder;
}
#Override
public void onBindViewHolder(PlatesAdapter.ViewHolder holder, int position) {
final TextView textView2 = holder.amountOfPlatesTextView;
//BUTTONS add 1 or subtract 1 from amountOfPlates;
Button button = holder.addButton;
Button button2 = holder.subButton;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
amountOfPlates++;
textView2.setText(Integer.toString(amountOfPlates));
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
amountOfPlates--;
textView2.setText(Integer.toString(amountOfPlates));
}
});
}
#Override
public int getItemCount() {
return mPlates.size();
}
Here is my Model Layer which i feel is completely wrong but im not 100% sure if it is.
public class Plates {
private int mPlateWeight;
private int mAmountOfPlates;
public Plates() {
//mPlateWeight = plateWeight;
//mAmountOfPlates = amountOfPlates;
}
public int getmPlateWeight() {
return mPlateWeight;
}
public int getmAmountOfPlates() {
return mAmountOfPlates;
}
public static List<Plates> createPlateList() {
List<Plates> plates = new ArrayList<>();
plates.add(new Plates());
return plates;
}
}
This is where im comfused. Its were do i call the addPlates or addItem method and what do i pass to it? Below is my main activity. I Just dont know where to add these addItems or addPlates methods is it to the Model Layer or the Adapter?
public class MainActivity extends AppCompatActivity {
private RecyclerView.LayoutManager mLayoutManager;
Button mButton;
private List<Plates> mData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button to add layout to recyclerView
mButton = (Button) findViewById(R.id.button);
//Adapter LayoutManager
mLayoutManager = new LinearLayoutManager(this);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.weights_recycler_view);
PlatesAdapter adapter = new PlatesAdapter(mData);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mLayoutManager);
}
});
}
}
What I usually do with RecyclerViews is to add a method to set the data.
In your example :
public void setPlates(List<Plates> plates) {
mPlates = plates;
notifyDataSetChanged();
}`
You can also add a getter if you want to verify if the data have changed or not.
You can add a method in your adapter to add a Plates in the arrayList and to notify the change.
Something like:
public void addPlates(Plates plate) {
if (mPlates == null) mPlates = new ArrayList();
mPlates.add(plate);
//notifyDataSetChanged();
notifyItemInserted(mPlates.size()-1)
}`
First of all the createPlateList method is not needed.
You should add a method in your adapter that looks like this:
public void addItem(Plates plate)
{
mPlates.add(plate);
}
Since your adapter works with this list, all you need to do to add or remove items, is to add/remove the items from your list. After all you need to call notifyDataSetChanged() in your adapter so it knows data was changed in your list.