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.
Related
I would like to create a simple application which has two activities. Activity A has recyclerview, and Activity B uploads the input data of edittexts. Creating recyclerview and passing data work well, but the view is not created more than 1. I would like to know what did I do wrong.
Activity A which has recyclerview.
public class MainActivity extends AppCompatActivity {
private ArrayList<MainData> list;
private MainAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
list = (ArrayList<MainData>) getIntent().getSerializableExtra("list");
adapter = new MainAdapter(list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Activity B which uploads data.
public class upload extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(upload.this, MainActivity.class);
ArrayList<MainData> list = new ArrayList<>();
EditText edit = (EditText) findViewById(R.id.edittext_name);
EditText edit_main = (EditText) findViewById(R.id.edittext_main);
list.add(new MainData(edit.getText().toString(), edit_main.getText().toString()));
intent.putExtra("list",list);
startActivity(intent);
finish();
}
});
Adapter :
public MainAdapter.CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
public void onBindViewHolder(#NonNull MainAdapter.CustomViewHolder holder, int position) {
//holder.iv_profile.setImageResource(list.get(position).getIv_profile());
holder.tv_name.setText(list.get(position).getTv_name());
holder.tv_content.setText(list.get(position).getTv_content());
holder.itemView.setTag(position);
#Override
public int getItemCount() {
return (null != list ? list.size() : 0);
}
public void remove(int position) {
try {
list.remove(position); //
notifyItemRemoved(position);
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView iv_profile;
protected TextView tv_name;
protected TextView tv_content;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
this.iv_profile = (ImageView) itemView.findViewById(R.id.iv_profile);
this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
this.tv_content = (TextView) itemView.findViewById(R.id.tv_content);
}
}
I tried several ways but always get a NPE due to difference in lifecycles etc
This is my MainActivity where I need to transfer a new Contact to the adapter
public class MainActivity extends AppCompatActivity {
private TextInputEditText textInputLastName;
private TextInputEditText textInputFirstName;
private TextInputEditText textInputMiddleName;
private TextInputEditText textInputAge;
private int age;
private TextInputLayout lastNameWrapper;
private TextInputLayout ageWrapper;
private ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastNameWrapper = findViewById(R.id.last_name_wrapper);
ageWrapper = findViewById(R.id.age_wrapper);
textInputLastName = findViewById(R.id.text_input_last_name);
textInputFirstName = findViewById(R.id.text_input_first_name);
textInputMiddleName = findViewById(R.id.text_input_middle_name);
textInputAge = findViewById(R.id.text_input_age);
addButtonMainActivity();
}
private void addButtonMainActivity() {
final Button buttonSendData = findViewById(R.id.button_send);
buttonSendData.setOnClickListener(view -> {
startActivity(new Intent(this, ShowDatabaseActivity.class));
if (textInputLastName.getText().toString().isEmpty()) {
lastNameWrapper.setError("Enter your Last Name");
return;
} else if (TextUtils.isEmpty(textInputAge.getText())) {
ageWrapper.setError("Enter your Age");
return;
}
age = Integer.parseInt(String.valueOf(textInputAge.getText()));
final Handler handler = new Handler();
Thread backgroundThread = new Thread(new Runnable() {
#Override
public void run() {
String lastName = textInputLastName.getText().toString();
String firstName = textInputFirstName.getText().toString();
String middleName = textInputMiddleName.getText().toString();
int age = Integer.parseInt(textInputAge.getText().toString());
Contact contact = new Contact(lastName, firstName, middleName, age);
AppDatabase.getINSTANCE(MainActivity.this).contactDao().insert(contact);
AppDatabase.getINSTANCE(MainActivity.this).contactDao().getAll();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addContact(contact);
}
});
}
});
backgroundThread.start();
});
}}
the line in question (this line is red now), where I need to transfer data to the adapter is
adapter.addContact(contact);
this is my 2nd activity that is used to initiated adapter's object and recycler view (and that is used to display database)
public class ShowDatabaseActivity extends AppCompatActivity {
private List<Contact> allContacts = new ArrayList<>();
public ContactsListAdapter adapter;
private ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_database);
setupToolbar();
initRecyclerView();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recycler_view);
adapter = new ContactsListAdapter(allContacts, ShowDatabaseActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
getTableData();
}
And this is my adapter class
public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
private Context context;
private List<Contact> contacts;
private LayoutInflater inflater;
public LayoutInflater getInflater() {
return inflater;
}
public ContactsListAdapter(#NonNull List<Contact> contacts, Context context) {
this.contacts = contacts;
this.context = context;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
return new ContactViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ContactViewHolder holder, int position) {
Contact currentContact = contacts.get(position);
if (currentContact != null) {
holder.contactLastNameView.setText(currentContact.getLastName());
holder.contactFirstNameView.setText(currentContact.getFirstName());
holder.contactMiddleNameView.setText(currentContact.getMiddleName());
holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
} else {
holder.contactLastNameView.setText("No information");
holder.contactFirstNameView.setText("No information");
holder.contactMiddleNameView.setText("No information");
holder.contactAgeView.setText("No information");
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
private final TextView contactLastNameView;
private final TextView contactFirstNameView;
private final TextView contactMiddleNameView;
private final TextView contactAgeView;
public TextView getContactLastNameView() {
return contactLastNameView;
}
public TextView getContactFirstNameView() {
return contactFirstNameView;
}
public TextView getContactMiddleNameView() {
return contactMiddleNameView;
}
public TextView getContactAgeView() {
return contactAgeView;
}
public ContactViewHolder(View itemView) {
super(itemView);
contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
contactAgeView = itemView.findViewById(R.id.age_text_view);
}
}
public void addContact(Contact contact) {
contacts.add(contact);
notifyDataSetChanged();
}
}
I would be really grateful for any help
You can't access adapter from your MainActivity, send you Contact data to the other Activity by using Intent's(putExtra) and use adapter.addContact() there.
Create a method in your activity like
public void showData(List<Contact> allContacts) {
//here you can show the data received from main activity
this.addContacts.addAll(allContacts);
adapter.notifyDataSetChanged();
}
you can call this method from MainActivity when you have data
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 have added cart image in my Adapter class but whenever I click on the button always get the last element from the list. Here is my adapter class and activity class.
Details are perfectly fetched from firebase and Log file showing list of menu.
Here is my MenuAdapter.java class.
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private Context mCtx;
private List<Menu> menuList;
private ItemClickEvent itemclick;
public MenuAdapter(Context mCtx, List<Menu> menuList, ItemClickEvent itemclick) {
this.mCtx = mCtx;
this.menuList = menuList;
this.itemclick = itemclick;
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(mCtx).inflate(R.layout.menu_list, viewGroup, false);
return new MenuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MenuViewHolder menuViewHolder, final int i) {
final Menu menu = menuList.get(i);
menuViewHolder.itemName.setText(menu.itemName);
menuViewHolder.itemPrice.setText(menu.itemPrice);
menuViewHolder.addCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemclick.imageClicked(menu);
}
});
}
#Override
public int getItemCount() {
return menuList.size();
}
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView itemName, itemPrice;
#SuppressLint("StaticFieldLeak")
ImageView addCart;
MenuViewHolder(#NonNull View itemView) {
super(itemView);
itemName = itemView.findViewById(R.id.itemName);
itemPrice = itemView.findViewById(R.id.itemPrice);
addCart = itemView.findViewById(R.id.menuAddCart);
//addCart.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
and this MenuActivity.java class
public class MenuActivity extends AppCompatActivity implements ItemClickEvent
{
private ActionBar toolbar;
List<Menu> menuList;
RecyclerView recyclerView;
MenuAdapter adapter;
DatabaseReference databaseReference;
ProgressBar progressBar;
Menu menu;
int foodId = 1;
int cat;
String id,itemName, itemPrice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent intent = getIntent();
final String category = intent.getStringExtra("cat_id");
final String catName = intent.getStringExtra("cat_name");
toolbar = getSupportActionBar();
toolbar.setTitle(catName);
cat = Integer.parseInt(category) - 1;
menuList = new ArrayList<>();
recyclerView = findViewById(R.id.menu_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MenuAdapter(this, menuList,this);
recyclerView.setAdapter(adapter);
ImageView addTCart = findViewById(R.id.menuAddCart);
progressBar = findViewById(R.id.progressBarLoading);
databaseReference = FirebaseDatabase.getInstance().getReference("foods/" + cat + "/menu-items");
// fetchMenu(category);
progressBar.setVisibility(View.VISIBLE);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.GONE);
if (dataSnapshot.exists()) {
for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {
id = wallpaperSnapshot.getKey();
itemName = wallpaperSnapshot.child("name").getValue(String.class);
itemPrice = wallpaperSnapshot.child("price").getValue(String.class);
menu = new Menu(id, itemName, itemPrice, category);
menuList.add(menu);
Log.d("FOOD-DETAIL", String.valueOf(menu));
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
Integer.parseInt(id),
menu.getItemName(),
"1",
menu.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}
#Override
public void viewClicked() {
}
}
Hello try making these changes in imageClicked() in MenuActivity
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
m.getId(),
m.getItemName(),
"1",
m.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}
There should be more efficient way to set listener. Just set that listener (same way as it is now) in constructor of MenuViewHolder and assign to this. And in method onClick - check R.id of view and if it is addCart instead of calling itemclick.imageClicked(menu) just call item.click.imageClicked(getAdapterPosition())
This because onBindViewHolder() is calling multiple times and you will still create new listener. But in constructor you create that listener only if you need new MenuViewHolder and use the actual position of adapter.
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();