Adding Toast to Every ChildItem of a Multi Level Expandable LisView - java

I found this multilevel expandable listview which is very accurate with my project, but I also want to add a different toast to every third level (which is the last layer of view) child items. I tried this:
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(thirdLevelq1.put(q1[0] this, "The first child" , Toast.LENGTH_LONG).show();
return false;
}
});
But it gives error. I even tried to use same toast text to every childItem, app installed but crashed when I opened the adapter. So, how to add them properly?
Java:
package com.bacon.expandablelistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
String[] parent = new String[]{"What is View?", "What is Layout?", "What is Dynamic Views?"};
String[] q1 = new String[]{"List View", "Grid View"};
String[] q2 = new String[]{"Linear Layout", "Relative Layout"};
String[] q3 = new String[]{"Recycle View"};
String[] des1 = new String[]{"A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen."};
String[] des2 = new String[]{"Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent)."};
String[] des3 = new String[]{"This list contains linear layout information"};
String[] des4 = new String[]{"This list contains relative layout information,Displays a scrolling grid of columns and rows"};
String[] des5 = new String[]{"Under the RecyclerView model, several different components work together to display your data. Some of these components can be used in their unmodified form; for example, your app is likely to use the RecyclerView class directly. In other cases, we provide an abstract class, and your app is expected to extend it; for example, every app that uses RecyclerView needs to define its own view holder, which it does by extending the abstract RecyclerView.ViewHolder class."};
LinkedHashMap<String, String[]> thirdLevelq1 = new LinkedHashMap<>();
LinkedHashMap<String, String[]> thirdLevelq2 = new LinkedHashMap<>();
LinkedHashMap<String, String[]> thirdLevelq3 = new LinkedHashMap<>();
/**
* Second level array list
*/
List<String[]> secondLevel = new ArrayList<>();
/**
* Inner level data
*/
List<LinkedHashMap<String, String[]>> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//The problem starts here
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), "The first child", Toast.LENGTH_LONG).show();
return false;
}
});
setUpAdapter();
}
private void setUpAdapter() {
secondLevel.add(q1);
secondLevel.add(q2);
secondLevel.add(q3);
thirdLevelq1.put(q1[0], des1);
thirdLevelq1.put(q1[1], des2);
thirdLevelq2.put(q2[0], des3);
thirdLevelq2.put(q2[1], des4);
thirdLevelq3.put(q3[0], des5);
data.add(thirdLevelq1);
data.add(thirdLevelq2);
data.add(thirdLevelq3);
expandableListView = (ExpandableListView) findViewById(R.id.expandible_listview);
//passing three level of information to constructor
ThreeLevelListAdapter threeLevelListAdapterAdapter = new ThreeLevelListAdapter(this, parent, secondLevel, data);
expandableListView.setAdapter(threeLevelListAdapterAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
int previousGroup = -1;
#Override
public void onGroupExpand(int groupPosition) {
if (groupPosition != previousGroup)
expandableListView.collapseGroup(previousGroup);
previousGroup = groupPosition;
}
});
}
}
Thanks in advance.
Edit: When I use Toast.makeText(getApplicationContext(), "The first child", Toast.LENGTH_LONG).show(); its crash logs says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setOnChildClickListener(android.widget.ExpandableListView$OnChildClickListener)' on a null object reference

#Override
public void onFinalChildClick(int plpos, int slpos, int tlpos) {
String msg = "";
switch (tlpos) {
case 0:
msg = "Shakespear is a good poet";
break;
case 1:
msg = "Earth isn't flat";
break;
default:
msg = "Unknown";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFinalItemClick(String plItem, String slItem, String tlItem) {
String inMsg = plItem + ", " + slItem + ", " + tlItem;
String outMsg = "";
if (inMsg.equals("group 1, Child Level 1, A")){
outMsg = "Shakespear is a good poet";
} else if (inMsg.equals("group 1, Child Level 1, B")){
outMsg = "Earth isn't flat";
} else {
outMsg = "Unknown";
}
Toast.makeText(this, outMsg, Toast.LENGTH_SHORT).show();
}

Please set this listener expandableListView.setOnChildClickListener after the expandableListView is initialized, that is after setUpAdapter() in your case as expandableListView is still null when you are trying to set the listener because your initialization of this is afterwards.
That is the reason for NullPointerException. because expandableListView is null while setting the listener.
Cheers

Related

How to retain the state of a recyclerview of list of custom objects?

Main Goal:-
I have a list of sports news. Each item contains a sport name and some info. Clicking on it will show the latest news regarding that particular sport. The user has the option to swipe to dismiss a news, if they don't want it in the list or they can also drag and drop it, for example, if they want to see some news on top of others.
Each item in the list is represented programmatically as a Sport.java object.
I want to retain the state of the list upon device orientation changes.
What I've tried:-
For the list, I have an arraylist of sport objects (ArrayList). I learned that to save a list of custom objects, they objects themselves need to be Parcelable. For this, I implemented the Parcelable.java interface like this:
package com.example.android.materialme;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
/**
* Data model for each row of the RecyclerView.
*/
class Sport implements Parcelable {
//Member variables representing the title and information about the sport
private String title;
private String info;
private String detail;
private final int imageResource;
/**
* Constructor for the Sport data model
* #param title The name if the sport.
* #param info Information about the sport.
*/
Sport(String title, String info, String detail, int imageResource) {
this.title = title;
this.info = info;
this.detail = detail;
this.imageResource = imageResource;
}
protected Sport(#NonNull Parcel in) {
title = in.readString();
info = in.readString();
detail = in.readString();
imageResource = in.readInt();
}
public static final Creator<Sport> CREATOR = new Creator<Sport>() {
#Override
public Sport createFromParcel(Parcel in) {
return new Sport(in);
}
#Override
public Sport[] newArray(int size) {
return new Sport[size];
}
};
String getTitle() {
return title;
}
String getInfo() {
return info;
}
int getImageResource(){
return imageResource;
}
String getDetail(){
return detail;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(info);
parcel.writeString(detail);
parcel.writeInt(imageResource);
}
}
and then I used
outState.putParcelableArrayList(KEY, sportsList);
but, this doesn't work. The screen is just blank upon rotating device.
I tried debugging the app and found that the arraylist was being passed correctly with the data intact, it's just that the app is not being able to display it for some reason.
Also, the implementation of the fab button is so that it resets the whole list to its initial condition upon click. The fab works normally but if the orientation is changed once, it stops working (app doesn't crash). Changing the orientation back also doesn't fix the fab. So, to get the list again for any other test, I have to rerun the entire app.
Complete Code:-
MainActivity.java
package com.example.android.materialme;
import android.content.res.TypedArray;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
//Member variables
private RecyclerView mRecyclerView;
private ArrayList<Sport> mSportsData;
private SportsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(view -> resetSports());
//Initialize the RecyclerView
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
//Set the Layout Manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Initialize the ArrayLIst that will contain the data
mSportsData = new ArrayList<>();
//Initialize the adapter and set it ot the RecyclerView
mAdapter = new SportsAdapter(this, mSportsData);
mRecyclerView.setAdapter(mAdapter);
initializeData(savedInstanceState);
ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
int from = viewHolder.getAdapterPosition();
int to = target.getAdapterPosition();
Collections.swap(mSportsData, from, to);
mAdapter.notifyItemMoved(from, to);
return true;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mSportsData.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
});
helper.attachToRecyclerView(mRecyclerView);
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("state", mSportsData);
}
/**
* Method for initializing the sports data from resources.
*/
private void initializeData(Bundle savedInstanceState) {
if(savedInstanceState!=null){
mSportsData.clear();
mSportsData = savedInstanceState.getParcelableArrayList("state");
} else {
//Get the resources from the XML file
String[] sportsList = getResources().getStringArray(R.array.sports_titles);
String[] sportsInfo = getResources().getStringArray(R.array.sports_info);
String[] sportsDetail = getResources().getStringArray(R.array.sports_detail);
TypedArray sportsImageResource = getResources().obtainTypedArray(R.array.sports_images);
//Clear the existing data (to avoid duplication)
mSportsData.clear();
//Create the ArrayList of Sports objects with the titles and information about each sport
for (int i = 0; i < sportsList.length; i++) {
mSportsData.add(new Sport(sportsList[i], sportsInfo[i], sportsDetail[i], sportsImageResource.getResourceId(i, 0)));
}
sportsImageResource.recycle();
}
//Notify the adapter of the change
mAdapter.notifyDataSetChanged();
}
public void resetSports(){
initializeData(null);
}
}
App Images:-
#1 Initial List
#2 Changed List (Card #2 for sport basketball is swiped)
Orientation change to landscape:-
Even though the question is 4 months old and you probably don't need the answer anymore:
The problem is that you initialize the adapter with mSportsData, but reassign another value to the variable later in initializeData(). The ArrayList bound to the adapter is still the empty one it got initialized with.
A way to solve it would be to initialize mSportsData with either a new ArrayList if savedInstanceState is null or else the saved value, and to call initializeData only if savedInstanceState is null. You can remove the argument and therefore the if from initalizeData() completely.
// Initialize the ArrayList that will contain the data.
if (savedInstanceState == null) {
mSportsData = new ArrayList<>();
} else {
mSportsData = savedInstanceState.getParcelableArrayList("state");
}
//Initialize the adapter and set it ot the RecyclerView (nothing changed here)
mAdapter = new SportsAdapter(this, mSportsData);
mRecyclerView.setAdapter(mAdapter);
if (savedInstanceState == null) {
initializeData();
}
Remove this function call from OnCreate initializeData(savedInstanceState); and call it in OnResume
I couldn't get it working with the Parcelable way so what I tried doing (and it worked) was save all the info contained inside all the sport objects in separate lists and put those in the bundle instead.
In the initialiseData(), I just used these lists then to create a new list of sport objects with the exact data.
This shouldn't be the way of doing it but my app just doesn't loads the saved list if it's passed as a parcelable and I don't know why.
Here's the working code for now:-
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<String> titles = new ArrayList<>();
ArrayList<String> infos = new ArrayList<>();
ArrayList<String> details = new ArrayList<>();
ArrayList<Integer> imgs = new ArrayList<>();
for(Sport sport: mSportsData){
titles.add(sport.getTitle());
infos.add(sport.getInfo());
details.add(sport.getDetail());
imgs.add(sport.getImageResource());
}
outState.putStringArrayList("title", titles);
outState.putStringArrayList("info", infos);
outState.putStringArrayList("detail", details);
outState.putIntegerArrayList("img", imgs);
}
private void initializeData(Bundle savedInstanceState) {
boolean hasData = false;
if(savedInstanceState!=null){
if(savedInstanceState.containsKey("title")){
//Get the resources from the bundle
ArrayList<String> sportsList = savedInstanceState.getStringArrayList("title");
ArrayList<String> sportsInfo = savedInstanceState.getStringArrayList("info");
ArrayList<String> sportsDetail = savedInstanceState.getStringArrayList("detail");
ArrayList<Integer> sportsImageResource = savedInstanceState.getIntegerArrayList("img");
//Clear the existing data (to avoid duplication)
mSportsData.clear();
//Create the ArrayList of Sports objects with the titles and information about each sport
for (int i = 0; i < sportsList.size(); i++) {
mSportsData.add(new Sport(sportsList.get(i), sportsInfo.get(i), sportsDetail.get(i), sportsImageResource.get(i)));
}
hasData = true;
}
}
if(!hasData) {
//Get the resources from the XML file
String[] sportsList = getResources().getStringArray(R.array.sports_titles);
String[] sportsInfo = getResources().getStringArray(R.array.sports_info);
String[] sportsDetail = getResources().getStringArray(R.array.sports_detail);
TypedArray sportsImageResource = getResources().obtainTypedArray(R.array.sports_images);
//Clear the existing data (to avoid duplication)
mSportsData.clear();
//Create the ArrayList of Sports objects with the titles and information about each sport
for (int i = 0; i < sportsList.length; i++) {
mSportsData.add(new Sport(sportsList[i], sportsInfo[i], sportsDetail[i], sportsImageResource.getResourceId(i, 0)));
}
sportsImageResource.recycle();
}
//Notify the adapter of the change
mAdapter.notifyDataSetChanged();
}

Why firebase recyclerview is not working correctly?

I try to open each video when I click on them but what I get instead is only the second video (sometimes first video). For example, when I click on "16 best video ideas for small business" I want it to open that particular video. But what I get instead is "this tiny camera can show the world from a bug's point of view. I think the problem occurs because of for loop inside query in UserHomeVideoAdapter.
UserHomeVideoAdapter.java:
public class UserHomeVideoAdapter extends FirestoreRecyclerAdapter<FollowList, UserHomeVideoAdapter.UserVideoHolder> {
Context context;
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String thumbUrl, videoTitle, videoUrl, videoDesc, videoId, publisherId;
Video video;
public UserHomeVideoAdapter(#NonNull #NotNull FirestoreRecyclerOptions<FollowList> options, Context context) {
super(options);
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull #NotNull UserVideoHolder holder, int position, #NonNull #NotNull FollowList model) {
Query query = db.collection("Videos").whereEqualTo("publisherId", model.getUserId());
query.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
if (task.getResult() != null) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
video = documentSnapshot.toObject(Video.class);
Log.d("Data", documentSnapshot.getId() + " => " + documentSnapshot.getData());
thumbUrl = video.getThumbUrl();
videoTitle = video.getVideoTitle();
videoUrl = video.getVideoUrl();
videoDesc = video.getVideoDesc();
videoId = video.getVideoId();
publisherId = video.getPublisherId();
}
if (task.getResult().size() != 0) {
Glide.with(context).load(model.getUserImageUrl()).into(holder.userProfileImage);
Glide.with(context).load(thumbUrl).into(holder.videoImageView);
holder.videoTitle.setText(videoTitle);
holder.mainContainerVideo.setVisibility(View.VISIBLE);
} else if (task.getResult().size() == 0) {
holder.mainContainerVideo.getLayoutParams().height = 0;
holder.mainContainerVideo.getLayoutParams().width = 0;
}
}
} else {
Toast.makeText(context, String.valueOf(task.getException()), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(e -> Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
holder.videoContainer.setOnClickListener(v -> {
Intent intent = new Intent(context, VideoActivity.class);
intent.putExtra("videoPublisherUserName", model.getUserName());
intent.putExtra("thumbUrl", thumbUrl);
intent.putExtra("videoPublisherEmail", model.getUserEmail());
intent.putExtra("videoUrl", videoUrl);
intent.putExtra("videoId", videoId);
intent.putExtra("videoPublisherFullName", model.getUserFullName());
intent.putExtra("videoPublisherId", publisherId);
context.startActivity(intent);
});
}
#NonNull
#NotNull
#Override
public UserVideoHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.video_cell, parent, false);
return new UserVideoHolder(v);
}
public static class UserVideoHolder extends RecyclerView.ViewHolder {
RelativeLayout videoContainer, mainContainerVideo;
CircleImageView userProfileImage;
TextView videoTitle;
ImageView videoImageView;
public UserVideoHolder(#NonNull #NotNull View itemView) {
super(itemView);
mainContainerVideo = itemView.findViewById(R.id.mainContainerVideo);
videoContainer = itemView.findViewById(R.id.videoContainer);
userProfileImage = itemView.findViewById(R.id.userProfileImage);
videoTitle = itemView.findViewById(R.id.videoTitle);
videoImageView = itemView.findViewById(R.id.videoImageView);
}
}
}
I logged videoId inside that is assigned inside for loop. Sometimes it returns ids in this order "1"; "2" and sometimes it returns like this "2"; "1". When it returns in this order "1"; "2" click opens second video even if I click first video and when it returns like this "2"; "1" click opens first video even if I click second video.
If you need additional code to solve the problem please ask and I will provide it as soon as possible. Any help is appreciated. Thanks
The short answer is that onBindViewHolder() is trying to do too much. From the documentation:
Called by RecyclerView to display the data at the specified position. This method should update the contents of the ViewHolder#itemView to reflect the item at the given position.
In other words, onBindViewHolder() is only responsible for one single item in the RecyclerView. However, you are trying to fetch all of the data for every element in the list. Instead, you should fetch the data external to your adapter and pass it in as a parameter. Then onBindViewHolder() should update the UI elements of a view inside the RecyclerView to display whatever you want for one single item.
Google has a great example CustomerAdapter. First, the constructor takes the list of data that will be displayed:
public CustomAdapter(String[] dataSet) {
mDataSet = dataSet;
}
Then onbindViewHolder() is only responsible for setting what is displayed in the UI of a single item in the RecyclerView:
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
}
It does NOT try to get data or loop over a list or anything else. All of that is someone else's responsibility.

Save data from fragments when switching tabs

I've written a game where the user inputs the number of player and every player gets an own tab with an empty table.
Therefore I used a PagerAdapterClass (extends FragmentStatePagerAdapter) and a viewpager.
So every player has the same fragmentView.
Now the user can put variables into the table, bu everytime I switch between the tabs, the input gets lost.
Well, i 'fixed' that problem by adding this to my pageradapter:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
But it's more stopping the viewpager from destroying than actually saving the data.
My main goal is to really save that stuff in that table.
I already tried https://stackoverflow.com/a/17135346/11956040 but i cannot get mContent because i cannot get the reference of the fragment, because all fragments are not created on their own but all at the same time (or something like that).
I also don't know how to set a Tag.
This way: https://stackoverflow.com/a/18993042/11956040
doesn't work for me.
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
...
//numPlayer = num of tabs
SectionsPagerAdapter adapter = new SectionsPagerAdapter(numPlayer, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
if(numPlayer >= 5) {
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
}
}
PagerAdapter:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private int tabNum;
public SectionsPagerAdapter(int tabNum, FragmentManager fm) {
super(fm);
this.tabNum = tabNum;
}
#Override
public PlaceholderFragment getItem(int position) {
return PlaceholderFragment.newInstance(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
int playerNum = position + 1;
return "Spieler " + playerNum;
}
#Override
public int getCount() {
// Show 2 total pages.
return tabNum;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
}
Fragment:
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt("player", index);
fragment.setArguments(bundle);
return fragment;
}
There must be a solution but I cannot find it or cannot implement it.
Pls help.
Solved my problem this way:
define 2 dimensional ArrayList for rows and columns and counter for columns:
private ArrayList<ArrayList<Integer>> columnArray;
private int column;
onCreateView (for fragments) set column = 0 and add one entry with an empty list to columnArray
and set the first rowList on column index of columnArray:
pointArray.add(column, new ArrayList<Integer>());
final ArrayList<Integer> rowList = pointArray.get(column);
fill the empty rowListwith 0 (maybe it also works in an other way, but I made it this way to have on empty EditTexts a 0 and can easily replace them)
define View.OnFocusChangeListener for all EditTexts like this:
/*I dont know if I could set column final in general,
but you need to set a final int because you call this value in an inner class*/
final int pos = column
for (int i = 0; i <= getEditTexts(pos).size() - 1; i++) {
EditText editTexts = getEditTexts(pos).get(i);
final String editTextsTag = editTexts.getTag().toString();
View.OnFocusChangeListener listener = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, final boolean b) {
if (view.getTag().toString().equals(editTextsTag) && !b) {
//fills rowList
addEntries(pos, rowList);
//adds rowList to columnArray
columnArray.set(pos, rowList);
//save the columnsArray or use it
saveData(columnArray);
}
}
};
editTexts.setOnFocusChangeListener(listener);
define method which collects data from each cell, depending on column position (pos), add it to rowList
for example:
private void addEntries(int pos, ArrayList<Integer> rowList) {
for(int i = 0; i <= 16; i++) {
//this requires EditText_label, i made them dynamically
String edit_label = "edit_" + pos + i;
EditText editText = table.findViewWithTag(edit_label);
String mEditTextString = editText.getText().toString();
try {
int thisValue = Integer.parseInt(mEditString);
rowList.set(j, thisValue);
} catch (NumberFormatException e) {
//maybe you do not need this, but I need it for something else
int thisValue = 0;
rowList.set(j, thisValue);
}
}
}
define a method for saving the columnArray. I used an interface to give it to parent Activity: Here you can find how I made it
Otherwise you can convert the columnArray to a String and save it in a database.
NOTE
I made it with column value set beacuse I increase the value for every column I add during runtime using a method. If you just have one column, you dont need to set it. Just use 0 instead of pos, column

Android Adapter not being updated

I want to display a list of match objects (match = two users having liked each other) in a recycler view with the help of an adapter.
This is my activity which is meant to display those matches:
public class MatchesActivity extends AppCompatActivity {
// variables:
private RecyclerView mMatchesRecyclerView;
private RecyclerView.Adapter mMatchItemAdapter;
private RecyclerView.LayoutManager mMatchesLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
mMatchesRecyclerView = findViewById(R.id.matches_recyclerView);
mMatchesRecyclerView.setNestedScrollingEnabled(false);
mMatchesRecyclerView.setHasFixedSize(true);
// set layout manager & pass it to the recycler view:
mMatchesLayoutManager = new LinearLayoutManager(MatchesActivity.this);
mMatchesRecyclerView.setLayoutManager(mMatchesLayoutManager);
// set match adapter & pass it to the recycler view:
mMatchItemAdapter = new MatchItemAdapter(getMatchesList(), MatchesActivity.this);
mMatchesRecyclerView.setAdapter(mMatchItemAdapter);
// add test items to the recycler view:
Match testMatch = new Match("abcdefgh");
matchesList.add(testMatch);
mMatchItemAdapter.notifyDataSetChanged();
Log.d("MatchesActivity", "TEST LIST: " + matchesList.toString());
}
private ArrayList<Match> matchesList = new ArrayList<Match>();
private List<Match> getMatchesList() {
Log.d("MatchesActivity", "getMatchesList function: " + matchesList.toString());
return matchesList;
}
}
And this is my adapter which is supposed to inflate the relevant layout & populate it with relevant object data:
public class MatchItemAdapter extends RecyclerView.Adapter<MatchViewholder> {
private List<Match> mMatchesList;
private Context mViewContext;
public MatchItemAdapter(List<Match> matchesList, Context context) {
this.mMatchesList = matchesList;
this.mViewContext = context;
Log.d("MatchItemAdapter", "Constructor: " + mMatchesList.toString());
}
// inflate the layout:
#Override
public MatchViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_matches, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
MatchViewholder matchViewholder = new MatchViewholder(layoutView);
Log.d("MatchItemAdapter", "onCreateViewHolder: " + mMatchesList.toString());
return matchViewholder;
}
// populate each row within the layout:
#Override
public void onBindViewHolder(MatchViewholder holder, int position) {
Log.d("MatchItemAdapter", "onBindViewHolder: " + mMatchesList.toString());
holder.mMatchID.setText(mMatchesList.get(position).getMatchID());
}
#Override
public int getItemCount() {
return 0;
}
}
The Match class currently only takes matchID parameter which is string. An object is created with a default image and this matchID string.
At the moment, I have no real match objects from database ready, so I wanted to check that the recycler view along with adapter are working as expected before i move on to that later.
However, when I go to Matches Activity, it is empty, showing nothing at all. As you can see from the MatchesActivity onCreate method, I created a test Match object with matchID = "abcdefgh" and then added that to the matchesList. So I am expecting the "abcdefgh" text to be passed to the adapter and to be shown in the MatchesActivity.
My log statements indicate that the Match object has been created and added to the list successfully, however, getMatchesList() function returns an empty list which is then used in the Adapter constructor too, (I think this is) causing Activity not show anything.
I am relatively new to Android and Java development, especially recycler view and adapters, but from what I gathered it seems to be as if the
mMatchItemAdapter.notifyDataSetChanged();
is not working properly as everything seems to be fine up until that point. Any help would be appreciated!
You're returning 0. What you should do instead is return the length of the mMatchesList list.
#Override
public int getItemCount() {
return mMatchesList.size();
}

notifyDataSetChanged() not working with custom Adapter View

I have seen this question answered a few times, however none of the fixes have worked for me, so i'm reaching out.
I have built an app that features the Diolor Swipeable Cards Library (here) and now am trying to implement Course Card Filters.
Essentially when a user clicks a course filter we want to change the data that is being fed to the adapter.
Currently I am trying to update the data and calling notifyDataSetChanged() on the adapter, expecting the cards to refresh to show the new data set, however am finding that it is not refreshing at all.
Any help with this would be hugely appreciated.
All code below is from my Main Activity.
I declare the data set that i will be feeding to the adapter at the top of the activity:
ArrayList<CourseCardModel> courseCardModelList;
then in my onCreate() method I instantiate the adapter, attach it to the view, and call a generateCourseCards() method which populates the courseCardModelList with objects pulled from a firebase database.
// Set up and assign card adapter
ca = new CustomCardAdapter(CardsActivity.this, android.R.layout.simple_list_item_1, generateCourseCards());
flingContainer.init(CardsActivity.this, ca);
generateCourseCards() method
private ArrayList<CourseCardModel> generateCourseCards() {
Toast.makeText(getApplicationContext(), "Retrieving Courses", Toast.LENGTH_LONG).show();
courseCardModelList = new ArrayList<CourseCardModel>();
dbref = FirebaseDatabase.getInstance().getReference().child("courses");
// Retrieve the course data from Firebase db and cast as Course object
dbref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e("Count " ,"" + snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
c = postSnapshot.getValue(Course.class);
System.out.println(c.getCourseName());
CourseCardModel model = new CourseCardModel();
model.setCourse(c);
courseCardModelList.add(model);
}
Collections.shuffle(courseCardModelList);
ca.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("The read failed: ", databaseError.getMessage());
}
});
return courseCardModelList;
}
Attempt to update the dataset (a simple shuffle for the time being) and refresh the cards
// Shuffle the collection and refresh the cards
Collections.shuffle(courseCardModelList);
ca.notifyDataSetChanged();
EDIT: added adapter code
public class CustomCardAdapter extends ArrayAdapter {
private TextView courseName, uniName, entryStandards, courseDuration, studyMode, qualification,
studentSatisfaction, gradProspects, t1, t2, t3, t4, t5, t6;
ArrayList<CourseCardModel> items;
View v;
LayoutInflater vi;
public CustomCardAdapter(Activity context, int resource, ArrayList<CourseCardModel> courses) {
super(context, resource, courses);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
v = convertView;
if (v == null) {
v = vi.inflate(R.layout.course_card_inner_template, parent , false);
}
CourseCardModel c = (CourseCardModel) getItem(position);
if (c != null) {
courseName = (TextView) v.findViewById(R.id.courseCardCourseName);
uniName = (TextView) v.findViewById(R.id.courseCardUniName);
entryStandards = (TextView) v.findViewById(R.id.courseCardEntryStandards);
courseDuration = (TextView) v.findViewById(R.id.courseCardCourseDuration);
studyMode = (TextView) v.findViewById(R.id.courseCardStudyMode);
qualification = (TextView) v.findViewById(R.id.courseCardQualification);
studentSatisfaction = (TextView) v.findViewById(R.id.courseCardStudentSatisfaction);
gradProspects = (TextView) v.findViewById(R.id.courseCardGraduateProspects);
t1 = (TextView) v.findViewById(R.id.cardTV1);
t2 = (TextView) v.findViewById(R.id.cardTV2);
t3 = (TextView) v.findViewById(R.id.cardTV3);
t4 = (TextView) v.findViewById(R.id.cardTV4);
t5 = (TextView) v.findViewById(R.id.cardTV5);
t6 = (TextView) v.findViewById(R.id.cardTV6);
v.setBackgroundResource(R.drawable.newcard);
courseName.setText(c.getCourse().getCourseName());
uniName.setText(c.getCourse().getUniversity());
entryStandards.setText(c.getCourse().getEntryStandards());
courseDuration.setText(c.getCourse().getCourseDuration());
studyMode.setText(c.getCourse().getStudyMode());
qualification.setText(c.getCourse().getQualification());
studentSatisfaction.setText(c.getCourse().getStudentSatisfaction().toString() + " / 5");
gradProspects.setText(c.getCourse().getGradProspects() + " / 100");
}
if(position ==0)
{
//float alpha = (float) 0.8;
//v.setAlpha(alpha);
courseName.setVisibility(View.VISIBLE);
}
else if (position == 1){
// Prepare the View for the animation
v.setVisibility(View.VISIBLE);
float alpha = (float) 0.8;
float alpha2 = (float) 0.3;
courseName.setAlpha(alpha2);
uniName.setAlpha(alpha2);
entryStandards.setAlpha(alpha2);
courseDuration.setAlpha(alpha2);
studyMode.setAlpha(alpha2);
qualification.setAlpha(alpha2);
studentSatisfaction.setAlpha(alpha2);
gradProspects.setAlpha(alpha2);
t1.setAlpha(alpha2);
t2.setAlpha(alpha2);
t3.setAlpha(alpha2);
t4.setAlpha(alpha2);
t5.setAlpha(alpha2);
t6.setAlpha(alpha2);
v.setAlpha(alpha);
}
else {
v.setVisibility(View.INVISIBLE);
}
return v ;
}
public void updateData(ArrayList<CourseCardModel> courseCardModels) {
this.items = courseCardModels;
notifyDataSetChanged();
}
}
Problem is in this method.
public void updateData(ArrayList<CourseCardModel> courseCardModels) {
this.items = courseCardModels;
notifyDataSetChanged();
}
here you are giving another array reference to your adapter.
Just rewrite as below.
public void updateData(ArrayList<CourseCardModel> courseCardModels) {
this.items.clear();
this.items.addAll(courseCardModels);
notifyDataSetChanged();
}
Without adapter class provided my first guess would be that you messed the references up. Maybe you are shuffling the data that is not referenced from the adapter. Once you share your adapter's code, I'll update my answer.
== EDIT ==
Avoid referencing some external collection of data from adapter, and updating that referenced data. Updating adapter/list data should be done using adapter's interface and methods such as add(), addAll() or remove() It might happen that (parent) adapter makes clone/copy of your data and in that case updating external/referenced collection is not doing any good.
You're extending an ArrayAdapter which holds his own array of models (the array passed to the constructor). If you would like to update the items, do something like this:
ca.clear();
for (CourseCardModel object : courseCardModelList) {
ca.insert(object, ca.getCount());
}
ca.notifyDataSetChanged();
Or you can override the getItem method and return an item from your items array.
And another option would be extending BaseAdapter instead of the ArrayAdapter.

Categories