Update Viewpager data dynamically - java

I have an ArrayList of my custom model class which I am instantiating by URL of images taken from Internet in my Home_Fragment using an AsyncTask
The first time the List is created it has 12 items/URL's from the website.
Now, I am passing these on a FullscreenView Activity that is linked to my ViewPager Adapter
-> I have set an onLoadMoreListener in my Home_Fragment that adds more items to the ArrayList, now I want to add those to my ViewPager Adapter dynamically,
How can I accomplish this?
Home_Fragment
class ReadHTML extends AsyncTask<String, Integer, String> {
List list;
#Override
protected String doInBackground(String... params) {
try {
Document document = Jsoup.connect(params[0]).get();
Element wall = document.select("ul.postul").first();
//Log.i("LIST ", wall.toString());
Elements url = wall.getElementsByAttribute("src");
list = url.eachAttr("src");
for (int i = 0; i < list.size(); i++) {
wallpaperNumber++;
String string = //Dummy
String septemp[] = //Dummy2
sep[1] = "http://" + string
wallpapersModelArrayList.add(new WallpapersModel(
string,///
sep[1],
"jpg",
wallpaperNumber
));
}
}catch (Exception e){}
return null;
}
Fullscreen Activity
setContentView(R.layout.fullscreen_activity_view);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
arrayList = getIntent().getParcelableArrayListExtra("array");
final int pos = getIntent().getIntExtra("position", 0);
fullScreenSwipeAdapter = new
FullScreenSwipeAdapter(FullWallpaperViewActivity.this, arrayList);
viewPager.setAdapter(fullScreenSwipeAdapter);
viewPager.setCurrentItem(pos);
viewPager.setOnTouchListener(new View.OnTouchListener(){}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {}
ViewPager Adapter
public FullScreenSwipeAdapter(Activity activity, ArrayList<WallpapersModel> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
Fresco.initialize(activity);
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.fullwallpaper_view_layout, container, false);
draweeView = v.findViewById(R.id.full_image_view);
draweeView.setImageURI(arrayList.get(position).getWallpaperFullURL());
container.addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((CoordinatorLayout)object);
}

First make a new instance of your ArrayAdapter and set all the new items like this:
public class Activity() extends AppCompatActivity {
CustomArrayAdapter mArrayAdapter;
ViewPager mViewPager;
public void updateViewpager(){
mArrayAdapter = new ArrayAdapter(context, itemList); // old items with new items
mViewPager.setAdapter(mArrayAdapter);
mArrayAdapter.notifyDataSetChanged();
}
...
Hope it helps,

After adding new items to ArrayList, just notify your adapter of the changes using -
arrayAdapter.notifyDataSetChanged();

Related

How to pass data from a fragment to an adapter

Let me quickly explain my code structure, I have a dynamic tab layout with a dynamic fragment. The tabs are fetched from a json response, and the each tab has a dynamic fragment with a recycler view populated from a json response as well.
I'm in trying to pass the id of the selected tab to the recycler view's adapter
1. TransactionsFragment(Where the tab layout is created)
for(int i=0;i<array.length();i++) {
//getting wallet object from json array
JSONObject userWallets=array.getJSONObject(i);
tab.addTab(tab.newTab().setText(userWallets.getString("wallet_name")));
walletID.add(userWallets.getInt("id"));
}
TransactionsPagerAdapter adapter = new TransactionsPagerAdapter
(getChildFragmentManager(), tab.getTabCount(), walletID); //the data i need to pass is the walletID
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
adapter.notifyDataSetChanged();
2. TransactionsPagerAdapter(adapter controlling the tabs)
public class TransactionsPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
ArrayList<Integer> walletID;
public TransactionsPagerAdapter(FragmentManager fm, int NumOfTabs, ArrayList<Integer> walletID) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mNumOfTabs = NumOfTabs;
this.walletID = walletID;
}
#Override
public Fragment getItem(int position) {
DynamicFragment d = new DynamicFragment();
Bundle args = new Bundle();
args.putInt("your_key", walletID.get(position));
d.setArguments(args);
return d.newInstance(walletID.get(position));
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
3. DynamicFragment(Where recycler view in each tab is populated)
for(int i=0;i<array.length();i++) {
//getting wallet object from json array
JSONObject userTransactions=array.getJSONObject(i);
//adding the wallet to wallet list
userTransactionList.add(new Transaction(
userTransactions.getInt("id"),
userTransactions.getInt("wallet_id"),
userTransactions.getDouble("fee"),
userTransactions.getDouble("amount"),
userTransactions.getDouble("from"),
userTransactions.getDouble("to"),
userTransactions.getString("destination_address"),
userTransactions.getString("type"),
userTransactions.getString("created_at")
));
}
//creating adapter object and setting it to recyclerview
TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);
mRecyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
// stop animating Shimmer and hide the layout
mShimmerViewContainer.stopShimmerAnimation();
mShimmerViewContainer.setVisibility(View.GONE);
// progressDialog.dismiss();
adapter.notifyDataSetChanged();
4. TransactionsAdapter(adapter controlling the recycler views)
public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.DataObjectHolder> {
private static String TAG = TransactionsAdapter.class.getSimpleName();
private Context mCtx;
private FragmentManager fragmentManager;
private ArrayList<Transaction> userTransactionList;
private static MyClickListener myClickListener;
public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList) {
this.mCtx = mCtx;
this.fragmentManager = fragmentManager;
this.userTransactionList = userTransactionList;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder {
TextView transactionamount, transactionstatus, transactionid;
ImageView transactionicon, pendingicon;
public DataObjectHolder(View itemView) {
super(itemView);
transactionamount = (TextView) itemView.findViewById(R.id.amount);
transactionstatus = (TextView) itemView.findViewById(R.id.status);
transactionicon = (ImageView) itemView.findViewById(R.id.tx_icon);
pendingicon = (ImageView) itemView.findViewById(R.id.img_status);
transactionid = (TextView) itemView.findViewById(R.id.wallet_id);
}
}
#Override
public TransactionsAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.transaction_item, parent, false);
final TransactionsAdapter.DataObjectHolder dataObjectHolder = new TransactionsAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(TransactionsAdapter.DataObjectHolder holder, final int position) {
DecimalFormat formatter = new DecimalFormat("###,###,###,###,###.##");
formatter.setDecimalSeparatorAlwaysShown(true);
formatter.setMinimumFractionDigits(2);
Double doubleBalance = userTransactionList.get(position).getTransactionAmount();
String numberFormatBalance = formatter.format(doubleBalance);
holder.transactionstatus.setText(userTransactionList.get(position).getTransactionType());
holder.transactionamount.setText(String.valueOf("₦ " + numberFormatBalance));
if ((userTransactionList.get(position).getTransactionType()).equals("send")) {
holder.transactionicon.setImageResource(R.drawable.ic_communication_call_made);
} else {
holder.transactionicon.setImageResource(R.drawable.ic_communication_call_received);
}
}
#Override
public int getItemCount() {
return userTransactionList.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
I need to get the walletID from 1(TransactionsFragment) to 4(TransactionsAdapter), is this possible, if so how, I know for a fact this cannot be done with bundle since we aren't creating an intent
Make sure you put walletId to Arguments of DynamicFragment by
DynamicFragment.newInstance(walletID.get(position))
Modify constructor of TransactionsAdapter follow this
private Integer walletId;
public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList, Integer walletId) {
this.mCtx = mCtx;
this.fragmentManager = fragmentManager;
this.userTransactionList = userTransactionList;
this.walletId = walletId;
}
In DynamicFragment when you init TransactionsAdapter get walletId from arguments of fragment
Integer walletId = getArguments().getInt("your_key") // your key when you newInstance and put to Bundle
TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);
Finally, your adapter has information of walletId

Cannot update RecyclerView inside a Fragment

I have an activity that uses a ViewPager to contain 2 Fragments. Inside one of the fragments I have a recyclerView. Until now When I first run the app the view is show correctly. The fragment makes a request to a web service and loads the data into the fragment's recyclerview and all good. Now my problem is that I must filter the data loaded into the recycler view from the MainActivity by just passing an Integer number but the recyclerview is not updating.
This is my code:
how I set my viewPager in MainActivity:
setSupportActionBar(toolbar);
ViewPagerAdapter adapterpager = new ViewPagerAdapter(getSupportFragmentManager(),context);
viewPager.setAdapter(adapterpager);
tabLayout.setupWithViewPager(viewPager);
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
Context context;
public ViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context=context;
}
#Override
public Fragment getItem(int position) {
ActivitiesFragment activitiesFragment = new ActivitiesFragment(context);
ArticlesFragment articlesFragment = new ArticlesFragment(context);
Fragment fragment = new Fragment();
if (position==0) {
fragment = activitiesFragment;
}else if (position==1){
fragment = articlesFragment;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
position = position+1;
String tabTittle="Activities";
if (position==2){
tabTittle = "Articles";
}
return tabTittle;
}
}
My ActivitiesFragment:
public class ActivitiesFragment extends Fragment implements ActivitiesResponse {
private RecyclerView activityRecycler;
private RequestMethods req;
private String skillId="1";
private String babyId="50";
Context context;
private ActivitiesRecyclerAdapter activitiesRecyclerAdapter;
public ActivitiesFragment(Context context) {
// Required empty public constructor
this.context=context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_activities, container, false);
activityRecycler = v.findViewById(R.id.activities_recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
activityRecycler.setLayoutManager(linearLayoutManager);
req = new RequestMethods(context);
req.getActivities(skillId,babyId,0);
req.onActivityResponse(this);
return v;
}
#Override
public void getActivities(List<Activity> list, int age) {
List<Activity> activityList = new ArrayList<>();
int listPos=0;
if (age==0){
activityList = list;
}else{
for (int x =0;x<list.size();x++){
if (list.get(x).getAge()==age){
activityList.add(listPos,list.get(x));
listPos++;
}
}
}
activitiesRecyclerAdapter = new ActivitiesRecyclerAdapter(activityList, context, new OnItemActivityClickListener() {
#Override
public void onItemClick(List<Activity> list, int position) {
Log.e("response_data","Click "+list.get(position).getName());
}
});
activityRecycler.setAdapter(activitiesRecyclerAdapter);
}
public void requestActivities(int age){
RequestMethods request = new RequestMethods(context);
request.onActivityResponse(this);
request.getActivities(skillId,babyId,age);
}
}
I have tried updating my Recyclerview using a the Override method getActivities(List<Activity> list, int age){} but nothing have worked till now. I have been stuck for hours please help!

Crash at listView.setAdapter(listAdapter) [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 6 years ago.
I did all the steps on this guide:
https://www.vlemonn.com/Blog/Android/Android-Custom-ListView-with-ImageView-EditText-and-Button/
The problem is that it crash at listView.setAdapter(listAdapter);
It gives me a NullPointerException() error.
Is there something that is not specified on the guide?
I put the code of the main class:
public class Prova extends AppCompatActivity implements CustomButtonListener {
// Declaring Your View and Variables
private ListView listView;
private ListAdapter listAdapter;
String[] arrItems, prices;
TypedArray images;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Antipasti","Primi piatti"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ordinazione_2);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle("Prova");
arrItems = getResources().getStringArray(R.array.fruitName);
images = getResources().obtainTypedArray(R.array.fruitImages);
prices = getResources().getStringArray(R.array.Price);
listView = (ListView) findViewById(R.id.customListView);
listAdapter = new ListAdapter(this,arrItems,images,prices);
listView.setAdapter(listAdapter);
listAdapter.setCustomButtonListener(this);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public void onButtonClickListener(int position,EditText editText, int value) {
/*
View view = listView.getChildAt(position);*/
int quantity = Integer.parseInt(editText.getText().toString());
quantity = quantity + 1 * value;
if(quantity<0)
quantity=0;
editText.setText(quantity + "");
}
then the ListAdapter.java
public class ListAdapter extends BaseAdapter {
//public ArrayList<HashMap<String, String>> listQuantity;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private String[] listViewItems,prices;
TypedArray images;
private Context context;
CustomButtonListener customButtonListener;
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
for(int i =0; i< listViewItems.length; i++ )
{
quantity.add(0);
//quantity[i]=0;
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.sis ,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvFruitName = (TextView) row.findViewById(R.id.textView4);
listViewHolder.ivFruit= (ImageView) row.findViewById(R.id.icon);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.prezzo);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.add);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editText2);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
listViewHolder.ivFruit.setImageResource(images.getResourceId(position, -1));
listViewHolder.tvPrices.setText(prices[position]);
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position,quantity.get(position) + 1);
}
}
});
//listViewHolder.edTextQuantity.setText("0");
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position,listViewHolder.edTextQuantity,-1);
if(quantity.get(position)>0)
quantity.set(position, quantity.get(position) - 1);
}
}
});
listViewHolder.tvFruitName.setText(listViewItems[position]);
return row;
}
Just looking at the code on that page, I see
android:id="# id/customListView"
Which should read
android:id="#+id/customListView"
The + is important as it tells Android to create a resource for it so you can do findViewById(R.id.customListView).
Either that or ordinazione_2.xml actually doesn't contain a #+id/customListView, in which case findViewById(R.id.customListView) will return null, thus your error.
As a matter of fact, all the layouts on that page have # id... You may want to try a better tutorial

ListView using BaseAdapter not showing in Activity

I'm trying to inflate a list using baseadapter within an activity. The list just doesn't inflate. From the logs implemented within the class, the getView() function doesn't even execute. Here's the code. -
public class CallLog extends Activity {
ListView logList;
List mList;
Context mCtx;
ArrayList<String> logName;
ArrayList<String> logNumber;
ArrayList<String> logTime;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.reject_call_log);
mCtx = getApplicationContext();
ListView logList = (ListView) findViewById(R.id.log_list);
mList = new List(mCtx, R.layout.log_row);
logList.setAdapter(mList);
SharedPreferences savedLogName = PreferenceManager.getDefaultSharedPreferences(mCtx);
SharedPreferences savedLogNumber = PreferenceManager.getDefaultSharedPreferences(mCtx);
SharedPreferences savedLogTime = PreferenceManager.getDefaultSharedPreferences(mCtx);
try{
logName = new ArrayList(Arrays.asList(TextUtils.split(savedLogName.getString("logName", null), ",")));
logNumber = new ArrayList(Arrays.asList(TextUtils.split(savedLogNumber.getString("logNumber", null), ",")));
logTime = new ArrayList(Arrays.asList(TextUtils.split(savedLogTime.getString("logTime", null), ",")));
Collections.reverse(logName);
Collections.reverse(logNumber);
Collections.reverse(logTime);
}catch(NullPointerException e){
e.printStackTrace();
//TextView noLog = (TextView)findViewById(R.id.no_log);
}
}
public class List extends BaseAdapter {
LayoutInflater mInflater;
TextView nameText;
TextView numberText;
TextView timeText;
int timePos = 1;
public List(Context context, int resource) {
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = mInflater.inflate(R.layout.row, null);
}
nameText = (TextView) v.findViewById(R.id.log_name);
numberText = (TextView) v.findViewById(R.id.log_number);
timeText = (TextView) v.findViewById(R.id.log_time);
nameText.setText(logName.get(position));
numberText.setText(logNumber.get(position));
timeText.setText(logTime.get(timePos) + logTime.get(timePos+1));
Log.d("RejectCall", "ListView");
timePos+=2;
return v;
}
}
}
Where is it all going wrong? Also, is there a better way to do what I'm trying to do?
Please replace the following code :
#Override
public int getCount() {
return 0;
}
with
#Override
public int getCount() {
return logName.size();
}
As list view only show the numbers of rows that is returned by this method and right now you are returning 0;
And after fetching the data in arraylist please use adapter.notifyDataSetChanged() to notify the list view.
You have to call notifyDataSetChanged() as you are filling data in array list after setting the adapter. so to notify the list view that data has been changed you have to call notify method(as above)
Your getItem() and getCount() haven't been implemented. If you want any kind of adapter to work for the list, these need to be implemented. Your list is also not holding any actual data, so getItem() has nothing to set.
Don't forget to call notifiyDataSetChanged() in your adapter after you set appropriate implementations for the above two functions.

ListView of ONLY drawables

I have a dynamic array of drawables and want to display them in a scrollable list. The thing I am having the most trouble with is the array adapter. I don't get any compile time errors with this code, but the runtime error I get is -
Process: com.example.michael.myandroidappactivity, PID: 12297
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
I don't want to use a textview though! Here's the main code-
public class cards extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_old_cards);
ListView list = (ListView)findViewById(R.id.showCardList);
cardPile tmp = cardPile.getInstance();
ArrayList<Integer> discardPile = tmp.getDiscardPile();
ArrayAdapter<Integer> imgAdapt = new ArrayAdapter<Integer>(this,R.layout.listview_layout,discardPile);
list.setAdapter(imgAdapt);
}
}
You have to create a new class that extends the BaseAdapter interface and modify the getView method to return the view you want to show in your ListView. For example:
public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Integer> imagesIds;
public ImageAdapter(Context _context, ArrayList<Integer> _imageIds)
{
context = _context;
imageIds = _imageIds;
}
#Override
public int getCount()
{
return imgIds.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView view;
if( convertView != null ) // recycle call
{
view = (ImageView) convertView;
}
else
{
view = new ImageView(context);
image.setBackgroundResource(imageIds.get(position));
}
return view;
}
}
Then modify your listView adapter as:
list.setAdapter( new ImageAdapter( this, discardPile) );

Categories