I am building a order receiving app for waiter in which half page is activity layout which contains listview and half is viewpager which contains json arraylist in fragment. I want to add the menu data from fragment when clicked on + button with number of quantity to be add on root activity's listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="140dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
app:layout_collapseMode="parallax"
android:background="#mipmap/bgactionbar">
<ImageView
android:id="#+id/logo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:background="#mipmap/logoapp"
/>
<ImageView
android:id="#+id/triangle"
android:layout_width="280dp"
android:layout_height="100dp"
android:layout_toRightOf="#+id/logo"
android:background="#mipmap/caley"
/>
<RelativeLayout
android:id="#+id/searchLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/triangle"
android:background="#F3EEE8"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_search"
android:layout_toRightOf="#+id/search_menu"
/>
<EditText
android:id="#+id/search_menu"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Search Menu..."
android:textColorHint="#color/tab_text"
android:textColor="#color/tab_text"
android:background="#android:color/transparent"
android:layout_alignParentLeft="true"
android:inputType="textVisiblePassword"/>
</RelativeLayout>
<ImageView
android:id="#+id/coffee"
android:layout_width="110dp"
android:layout_height="140dp"
android:layout_toRightOf="#+id/searchLayout"
android:background="#mipmap/coffee"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
android:background="#mipmap/background"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="#mipmap/background"
android:layout_below="#id/My_Container_1_ID">
<TextView
android:id="#+id/txtorder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Order"
android:textStyle="bold"
android:textColor="#color/tab_text"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/orderlist"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_above="#+id/submit_order"
android:layout_below="#+id/txtorder"
android:background="#mipmap/background"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<Button
android:id="#+id/submit_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/orderlist"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/orderlist"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#EE6426"
android:textColor="#android:color/white"
android:text="Submit" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="#+id/My_Container_1_ID"
android:layout_toRightOf="#+id/content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
public class Menu extends AppCompatActivity implements Coffee.OnMenuInteractionListener {
// private ArrayList<MenuDataModel> allOrders;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ListView listView;
RecyclerView recyclerView;
RecyclerAdapter adapter;
// MenuTabAdapter adapter;
// ArrayList<MenuDataModel> allOrders;
private List<MenuDataModel> allOrders = new ArrayList<MenuDataModel>();
// private List<String> orderList = new ArrayList<>();
private String Quantity, Name;
EditText count, inputSearch;
TextView order;
String searchValue;
private ArrayList<String> stringArrayList;
CollapsingToolbarLayout collapsingToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbar= (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// collapsingToolbar.setTitle(getString(R.string.app_name));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// listView = (ListView) findViewById(R.id.orderlist);
// adapter = new MenuTabAdapter(this, allOrders);
// listView.setAdapter(adapter);
TextView orddd = (TextView) findViewById(R.id.txtorder);
inputSearch = (EditText) findViewById(R.id.search_menu);
// inputSearch.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// collapsingToolbar.setVisibility(View.GONE);
//
// }
// });
// recyclerView = (RecyclerView) findViewById(R.id.orderlist);
// recyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
//
// adapter = new RecyclerAdapter(this, allOrders);
// recyclerView.setAdapter(adapter);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Coffee(), "Coffee");
adapter.addFragment(new Coffee(), "BreakFast");
adapter.addFragment(new Coffee(), "Beverage");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList) {
allOrders = menuList;
}
#Override
public void onMenuListItemClick(int position) {
//musicService.setSong(position);
MenuDataModel menuorder = allOrders.get(position);
// menuorder.setName(menuorder.getName());
// menuorder.setName(allOrders);
allOrders.add(menuorder);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class Coffee extends Fragment {
ListView listView;
MenusAdapter adapter;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<MenuDataModel> menuList = new ArrayList<MenuDataModel>();
OnMenuInteractionListener menuItemClick;
private String searchData;
private EditText inputSearch;
// Activity activity;
//OnMenuInteractionListener mCallback;
public Coffee() {
// Required empty public constructor
}
public interface OnMenuInteractionListener {
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList);
public void onMenuListItemClick(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
menuItemClick = (OnMenuInteractionListener) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
menuItemClick = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// searchData = getArguments().getString("search");
inputSearch = (EditText) getActivity().findViewById(R.id.search_menu);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user changed the Text
//adapter.getFilter().filter(cs.toString());
if (count < before) {
// We're deleting char so we need to reset the adapter data
adapter.resetData();
}
Coffee.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
View view = inflater.inflate(R.layout.fragment_coffee, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MenusAdapter(getActivity(), menuList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showpDialog();
// Creating volley request obj
JsonObjectRequest bookingReq = new JsonObjectRequest(Request.Method.GET, "" + url + "?", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("bsd", response.toString());
// Parsing json
try {
JSONArray menu = response.getJSONArray("menus");
int length = menu.length();
for (int i = 0; i < menu.length(); i++) {
JSONObject obj = menu.getJSONObject(i);
MenuDataModel dm = new MenuDataModel();
// Log.d("vdata", String.valueOf(menu.length()));
dm.setID(obj.getString("id"));
dm.setName(obj.getString("name"));
dm.setThumbnailUrl(obj.getString("photo"));
Log.d("image", String.valueOf(obj.getString("photo")));
dm.setDescription(obj.getString("description"));
dm.setRate(obj.getString("price"));
dm.setStatus(obj.getString("status"));
// adding movie to movies array
menuList.add(dm);
// Log.d("nth", String.valueOf(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#SuppressWarnings("deprecation")
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("b", "Error: " + error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookingReq);
return view;
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.setMessage("Please wait...");
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class MenusAdapter extends BaseAdapter implements Filterable {
private static final String TAG = MenusAdapter.class.getSimpleName();
List<MenuDataModel> MenuItems;
List<MenuDataModel> mSearchValues;
private android.widget.Filter menufilter;
Coffee.OnMenuInteractionListener mCallback;
//private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MenusAdapter(Activity activity, List<MenuDataModel> MenuItems) {
//this.activity = activity;
this.MenuItems = MenuItems;
this.mSearchValues = MenuItems;
}
#Override
public int getCount() {
return MenuItems.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return MenuItems.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_item, parent, false);
}
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
final ImageView increase = (ImageView) view.findViewById(R.id.icon_increase);
ImageView decrease = (ImageView) view.findViewById(R.id.icon_decrease);
final EditText count = (EditText) view.findViewById(R.id.count_menu);
NetworkImageView thumbnailUrl = (NetworkImageView) view.findViewById(R.id.menu_image);
TextView name = (TextView) view.findViewById(R.id.menu_items);
// TextView description = (TextView) view.findViewById(R.id.description);
// TextView rate = (TextView) view.findViewById(R.id.price);
final MenuDataModel data = MenuItems.get(index);
name.setText(String.valueOf(data.getName()));
thumbnailUrl.setImageUrl(data.getThumbnailUrl(), imageLoader);
thumbnailUrl.setDefaultImageResId(R.mipmap.logoapp);
thumbnailUrl.setErrorImageResId(R.mipmap.logoapp);
// description.setText(String.valueOf(data.getDescription()));
// title.setText(data.getTitle());
// rate.setText(String.valueOf(data.getRate()));
// final double dis = Double.valueOf(data.getRate());
final int[] quantity = {MenuItems.get(index).getAnInt()};
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
quantity[0]++;
count.setText(quantity[0] + "");
count.setTag(quantity[0] + "");
// mCallback.onFragmentSetOrders(all);
mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
// Coffee.OnMenuInteractionListener listener = (Coffee.OnMenuInteractionListener) activit;
// mCallback.onFragmentSetOrders(menu);
// Bundle bundle = new Bundle();
// bundle.putString("quantity", quantity[0] + "");
// bundle.putString("name", String.valueOf(data.getName()));
// q.putExtra("bookingid", dataModel.getbkid());
// parent.getContext().startActivity(q);
}
});
decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count.getTag();
count.setTag(quantity[0] + "");
quantity[0]--;
count.setText(quantity[0] + "");
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public Filter getFilter() {
if (menufilter == null)
menufilter = new MenuFilter();
return menufilter;
}
public void resetData() {
MenuItems = mSearchValues;
}
private class MenuFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mSearchValues;
results.count = mSearchValues.size();
} else {
// We perform filtering operation
List<MenuDataModel> nDriverList = new ArrayList<MenuDataModel>();
for (MenuDataModel p : MenuItems) {
if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nDriverList.add(p);
}
results.values = nDriverList;
results.count = nDriverList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
MenuItems = (List<MenuDataModel>) results.values;
notifyDataSetChanged();
}
}
}
;
}
i am getting null pointer exception on mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
Step 1: Create Interface
public interface ActivityCommunicator{
public void passDataToActivity(ArrayList<string> arrayList);
}
Step 2:Initialize interface object in fragment class
private ActivityCommunicator activityCommunicator;;
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = getActivity();
activityCommunicator =(ActivityCommunicator)context;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
activityButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
activityCommunicator.passDataToActivity("Your Array List");
}
});
}
step 3: Access Your arraylist from fragment in your activity class.
public class MainActivity extends FragmentActivity implements ActivityCommunicator{
public static ArrayList<String> aList;
#Override
public void passDataToActivity(ArrayList<String> arrayList){
aList = arrayList;
}
}
Related
I have silder layout.xml in rss fragment. I do not know how to call them in fragment. I need to put some rss feed one link and get the data. Let me know if you know anyone
EnchantedViewPager
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
Rss feed layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp">
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator_unselected_background"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="5dp"
android:layout_marginEnd="10dp"
app:ci_drawable="#drawable/selecteditem_dot"
app:ci_drawable_unselected="#drawable/nonselecteditem_dot"
app:ci_height="6dp"
app:ci_width="6dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/background_white"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
style="#style/listStyleNoPadding"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<com.facebook.shimmer.ShimmerFrameLayout
android:id="#+id/shimmer_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:shimmer_duration="1000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/lyt_shimmer_recipes_list_big"
layout="#layout/include_shimmer_recipes_list_big" />
</RelativeLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
</RelativeLayout>
RssFragment
public class RssFragment extends Fragment {
// Added argument key for URL
private static final String ARG_URL = "url_string";
public static final int RECIPES_LIST_SMALL = 0;
public static final int RECIPES_LIST_BIG = 1;
public static final int RECIPES_GRID_2_COLUMN = 2;
public static final int RECIPES_GRID_3_COLUMN = 3;
private RSSFeed rssFeed = null;
private ArrayList<RSSItem> postsList;
private RssAdapter listAdapter;
private ViewModeUtils viewModeUtils;
private SwipeRefreshLayout swipeRefreshLayout;
SharedPref sharedPref;
private Activity mAct;
private RelativeLayout ll;
private String url;
private AdView mAdView;
private View rootView;
private ShimmerFrameLayout lyt_shimmer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_list_refresh, container, false);
return ll;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
lyt_shimmer = ll.findViewById(R.id.shimmer_view_container);
RecyclerView listView = ll.findViewById(R.id.list);
postsList = new ArrayList<>();
listAdapter = new RssAdapter(getContext(), postsList);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
listView.setAdapter(listAdapter);
listView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
swipeRefreshLayout = ll.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshItems();
initShimmerLayout();
}
private void initShimmerLayout() {
View lyt_shimmer_recipes_list_big = ll.findViewById(R.id.lyt_shimmer_recipes_list_big);
if (sharedPref.getRecipesViewType() == RECIPES_LIST_SMALL) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_LIST_BIG) {
lyt_shimmer_recipes_list_big.setVisibility(View.VISIBLE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_2_COLUMN) {
;
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_3_COLUMN) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
}
}
});
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
// get URL from arguments
url = RssFragment.this.getArguments().getString(ARG_URL);
refreshItems();
}
private class RssTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
// Pass the URL string as parameter to URL class
URL rssUrl = new URL(url);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
rssFeed = myRSSHandler.getFeed();
} catch (ParserConfigurationException | IOException | SAXException e) {
Log.printStackTrace(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (rssFeed != null) {
if (rssFeed.getList().size() > 0) {
postsList.addAll(rssFeed.getList());
}
listAdapter.setHasMore(false);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_LIST);
swipeRefreshLayout.setRefreshing(false);
} else {
String message = null;
if (!url.startsWith("http"))
message = "Debug info: '" + url + "' is most likely not a valid RSS url. Make sure the url entered in your configuration starts with 'http' and verify if it's valid XML using validator.w3.org/feed";
Helper.noConnection(mAct, message);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_EMPTY);
swipeRefreshLayout.setRefreshing(false);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
viewModeUtils = new ViewModeUtils(getContext(), getClass());
viewModeUtils.inflateOptionsMenu(menu, inflater);
ThemeUtils.tintAllIcons(menu, mAct);
}
private void refreshItems() {
postsList.clear();
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
new RssTask().execute(
);
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
return;
}
swipeRefreshLayout.post(() -> {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.VISIBLE);
lyt_shimmer.startShimmer();
});
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
lyt_shimmer.stopShimmer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
viewModeUtils.handleSelection(item, new ViewModeUtils.ChangeListener() {
#Override
public void modeChanged() {
listAdapter.notifyDataSetChanged();
}
});
switch (item.getItemId()) {
case R.id.info:
//show information about the feed in general in a dialog
if (rssFeed != null) {
String FeedTitle = (rssFeed.getTitle());
String FeedDescription = (rssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (rssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")) {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription);
} else {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription +
"\n\n" + linkvalue + ": \n" + FeedLink);
}
builder.setNegativeButton(getResources().getString(R.string.ok), null)
.setCancelable(true);
builder.create();
builder.show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}}
// This is the factory to instantiate the RssFragment instance with the url string as arguments
public static RssFragment newInstance(String url) {
RssFragment newInstance = new RssFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_URL, url);
newInstance.setArguments(bundle);
return newInstance;
}
}
ScrollableTabsActivity
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847959/rss.xml"), "உலகம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847980/rss.xml"), "சினிமா");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850122/rss.xml"), "வேலை வாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850077/rss.xml"), "டெக்னாலஜி");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850128/rss.xml"), "சமையலறை");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850092/rss.xml"), "விவசாயம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850103/rss.xml"), "கல்வி-வேலைவாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850110/rss.xml"), "விளையாட்டு");
viewPager.setAdapter(adapter);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
I need to put an rss feed link to something and get the data.
I am doing one application. In that i need to search the recycler item and once the user selects item from recycler then it should be set as a tag to that edit text. I did this from this https://android-arsenal.com/details/1/3581, but its not working properly. Can any help me how can i achieve the searching the items from recycler view and set it as a edit tag for that selected item.
This is the screen for reference.
I am doing like this
public class ActivityTagFriends extends BaseActivity implements TagsEditText.TagsEditListener, View.OnClickListener {
TextView tv_cancel, tv_title, tv_Done;
RecyclerView rv_TagFriends;
private TagsEditText mTagsEditText;
private List<String> list = new ArrayList<String>();
TagFriendsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tag_friends);
tv_cancel = (TextView) findViewById(R.id.tvCancel);
tv_cancel.setText("Cancel");
tv_cancel.setTextColor(getResources().getColor(R.color.red));
tv_title = (TextView) findViewById(R.id.tvTitle);
tv_title.setText("Tag Friends");
tv_title.setTextColor(getResources().getColor(R.color.black));
tv_Done = (TextView) findViewById(R.id.tvDone);
tv_Done.setText("Done");
tv_Done.setTextColor(getResources().getColor(R.color.red));
rv_TagFriends= (RecyclerView) findViewById(R.id.rv_TagFriends);
mTagsEditText = (TagsEditText) findViewById(R.id.tagsEditText);
mTagsEditText.setHint("Search");
mTagsEditText.setTagsListener(this);
mTagsEditText.setTagsWithSpacesEnabled(true);
mTagsEditText.setAdapter(new ArrayAdapter<>(this,
R.layout.tag_friends_row, R.id.tv_TagName,list));
mTagsEditText.setThreshold(1);
rv_TagFriends.setHasFixedSize(true);
rv_TagFriends.setLayoutManager(new LinearLayoutManager(this));
countryList(); // in this method, Create a list of items.
// call the adapter with argument list of items and context.
// mAdapter = new TagFriendsAdapter(list,this);
// rv_TagFriends.setAdapter(mAdapter);
addTextListener();
}
// this method is used to create list of items.
public void countryList(){
list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}
public void addTextListener(){
mTagsEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final List<String> filteredList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final String text = list.get(i).toLowerCase();
if (text.contains(query)) {
filteredList.add(list.get(i));
}
}
rv_TagFriends.setLayoutManager(new LinearLayoutManager(ActivityTagFriends.this));
mAdapter = new TagFriendsAdapter(filteredList, ActivityTagFriends.this);
rv_TagFriends.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
// data set changed
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// mTagsEditText.showDropDown();
// data set changed
}
}
#Override
public void onClick(View v) {
}
#Override
public void onTagsChanged(Collection<String> tags) {
}
#Override
public void onEditingFinished() {
}
}
Thanks in advance.
Okay I got your problem use this code
Your activity layout(activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:TagsEditText="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="mabbas007.myapplication.MainActivity">
<mabbas007.tagsedittext.TagsEditText
android:id="#+id/tagsEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
TagsEditText:allowSpaceInTag="true"
TagsEditText:tagsBackground="#drawable/square_default"
TagsEditText:tagsCloseImageRight="#drawable/tag_close" />
<TextView
android:background="#android:color/darker_gray"
android:padding="10dp"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Suggestion"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
adapter layout(adapter_item.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:padding="10dp"
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:layout_height="1dp"/>
</LinearLayout>
Activity code
public class MainActivity extends AppCompatActivity
implements TagsEditText.TagsEditListener {
RecyclerView rv_TagFriends;
private TagsEditText mTagsEditText;
private List<String> list = new ArrayList<String>();
TagFriendsAdapter mAdapter;
ArrayList<String > tags;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tags=new ArrayList<>();
rv_TagFriends= (RecyclerView) findViewById(R.id.rv);
mTagsEditText = (TagsEditText) findViewById(R.id.tagsEditText);
mTagsEditText.setHint("Search");
mTagsEditText.setTagsListener(this);
mTagsEditText.setTagsWithSpacesEnabled(true);
//mTagsEditText.setAdapter(mAdapter);
mTagsEditText.setThreshold(1);
rv_TagFriends.setHasFixedSize(true);
rv_TagFriends.setLayoutManager(new LinearLayoutManager(this));
countryList(); // in this method, Create a list of items.
// call the adapter with argument list of items and context.
// mAdapter = new TagFriendsAdapter(list,this);
// rv_TagFriends.setAdapter(mAdapter);
addTextListener();
}
// this method is used to create list of items.
public void countryList(){
list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}
public void addTextListener(){
mTagsEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase().trim();
if (query.toString().equals(""))
return;
if (tags.size()!=0)
query=query.toString().substring(query.toString().indexOf(tags.get(tags.size()-1).toLowerCase())+tags.get(tags.size()-1).toString().length()).trim();
if (query.toString().equals("")){
final List<String> filteredList = new ArrayList<>();
rv_TagFriends.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new TagFriendsAdapter(filteredList, MainActivity.this);
rv_TagFriends.setAdapter(mAdapter);
}else {
final List<String> filteredList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final String text = list.get(i).toLowerCase();
if (text.contains(query)) {
filteredList.add(list.get(i));
}
}
rv_TagFriends.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new TagFriendsAdapter(filteredList, MainActivity.this);
rv_TagFriends.setAdapter(mAdapter);
}
}
});
}
#Override
public void onTagsChanged(Collection<String> tags) {
}
#Override
public void onEditingFinished() {
}
public class TagFriendsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<String > data;
private MainActivity mainActivity;
public TagFriendsAdapter(List<String> data , MainActivity mainActivity) {
this.data = data;
this.mainActivity=mainActivity;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_item, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
((MyViewHolder)holder).text.setText(data.get(position)+"");
((MyViewHolder)holder).text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainActivity.add(data.get(position)+"");
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView text;
public MyViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
}
}
}
public void add(String s){
for (int i = 0; i < tags.size(); i++) {
if (s.equals(tags.get(i)))
return;
}
tags.add(s);
String [] tag=tags.toArray(new String [0]);
mTagsEditText.setTags(tag);
}
}
I know that this question was asked many times before, but i'm confused why sometimes the data is loaded and sometimes data isn't loaded once i get to the end of list. Also when i go fast scrolling through the list, and the new data has been loaded, but immediately it returns me to the first item in list and remove all new loaded items from the next page from server. So that is the second problem and the third problem is that when i load items using SwipeRefreshLayout, i'm also not getting new items when i reach the end of the list.
I have implemented this in my project: https://gist.github.com/ssinss/e06f12ef66c51252563e
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
loadJokes(1);
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
Here is the method where i'm loading more items from server:
private void loadMoreJokes(int current_page) {
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + current_page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And here is the method where i'm loading first visible items when someone launch the app:
private void loadJokes(int page) {
pDialog.setMessage("Loading..");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mJokes.clear();
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
menu.showMenu(true);
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And this is onRefresh() method:
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
refreshItems();
}
}, 5000);
}
private void refreshItems() {
loadJokes(1);
mSwipeRefreshLayout.setRefreshing(false);
}
If i need to post more code, let me know. I really need to solve this problem as soon as i can. So again, the problems are the following:
When fast scrolling through the list, new items are being loaded, but immediately after that it returns me to the beginning of the list and when i go to the end of list again, load more doesn't respond.
After refreshing the list with SwipRefreshLayout, also scrolling doesn't respond at the end.
Note: The scrolling and loading new items is working only if i go slowly through the list and if i didn't swipe to refresh list.
EDIT:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_jokes, container, false);
mContext = getActivity();
mView = (CoordinatorLayout) view.findViewById(R.id.coordinatorLayout);
TextView tvEmptyText = (TextView) view.findViewById(R.id.tv_empty);
ImageView ivSignal = (ImageView) view.findViewById(R.id.iv_signal);
if (!ConnectionDetector.getInstance(getActivity()).isOnline() && mAdapter == null) {
tvEmptyText.setVisibility(View.VISIBLE);
ivSignal.setVisibility(View.VISIBLE);
showNoInternetSnackbar();
}
// INITIALIZE RECYCLER VIEW
EmptyRecyclerView list = (EmptyRecyclerView) view.findViewById(R.id.list);
mJokes = new ArrayList<>();
mAdapter = new RecyclerJokesAdapter(getActivity(), mJokes, JokesFragment.this, null);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
showDialog();
View emptyView = inflater.inflate(R.layout.layout_empty_view, container, false);
FloatingActionButton fab1 = (FloatingActionButton) view.findViewById(R.id.fab_funny);
FloatingActionButton fab2 = (FloatingActionButton) view.findViewById(R.id.fab_good_morning);
FloatingActionButton fab3 = (FloatingActionButton) view.findViewById(R.id.fab_good_night);
FloatingActionButton fab4 = (FloatingActionButton) view.findViewById(R.id.fab_all);
menu = (FloatingActionMenu) view.findViewById(R.id.menu_sort_jokes);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
fab3.setOnClickListener(this);
fab4.setOnClickListener(this);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(
R.color.refresh_progress_1,
R.color.refresh_progress_2,
R.color.refresh_progress_3);
LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
if (ConnectionDetector.getInstance(mContext).isOnline()) {
loadJokes(1);
} else {
showNoInternetSnackbar();
hideDialog();
}
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
return view;
}
In onCreate method initialize your adapter, recyclerView and List
List<MyObject> myList = new ArrayList<>();
recyclerViewAdapter = new RecyclerViewAdapter(context, myList)
myRecyclerView.setAdapter(recyclerViewAdapter);
Now, whenever you load data. add the data to your myList and call notifyDataSetChange on your adpater
myList.add(data);
recyclerViewAdapter.notifyDataSetChange();
Use this wrapper class
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public abstract class RecyclerWrapperAdapter<E> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected Context context;
protected List<E> objects;
public void setContext(Context context) {
this.context = context;
}
public void setObjects(List<E> objects) {
this.objects = objects;
notifyDataSetChanged();
}
public void add(#NonNull E object) {
objects.add(object);
notifyDataSetChanged();
}
public void add(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.add(position, object);
notifyItemChanged(position);
notifyDataSetChanged();
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void set(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.set(position, object);
notifyItemChanged(position);
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void remove(#NonNull E object) {
objects.remove(object);
notifyDataSetChanged();
}
public void remove(int position) {
if (position >=0 && position < objects.size()) {
objects.remove(position);
notifyDataSetChanged();
}
}
public void removeAll() {
objects.clear();
notifyDataSetChanged();
}
public E getItem(int position) {
return objects.get(position);
}
#Override
public int getItemCount() {
return objects.size();
}
}
Well I have done this way:
MainActivity .java
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, onRecyclerViewListener {
private RecyclerView mRecyclerView;
private TextView tvEmptyView;
private LinearLayoutManager mLayoutManager;
private List<Object> studentList;
protected Handler handler;
private int count = 0;
private SwipeRefreshLayout swipeRefreshLayout;
private MyRecycleAdapter myRecycleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.purple, R.color.green, R.color.orange);
tvEmptyView = (TextView) findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
studentList = new ArrayList<Object>();
handler = new Handler();
loadData();
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
myRecycleAdapter = new MyRecycleAdapter(mRecyclerView, studentList, R.layout.list_row, R.layout.progressbar_item, this);
myRecycleAdapter.setLoadMoreEnable(true);
myRecycleAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
count++;
if (count == 4) {
count = 0;
myRecycleAdapter.setLoadMoreEnable(false);
} else {
myRecycleAdapter.setLoadMoreEnable(true);
}
//add null , so the adapter will check view_type and show progress bar at bottom
studentList.add(null);
myRecycleAdapter.notifyItemInserted(studentList.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
studentList.remove(studentList.size() - 1);
myRecycleAdapter.notifyItemRemoved(studentList.size());
//add items one by one
int start = studentList.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
studentList.add(new Student("Student " + i, "AndroidStudent" + i + "#gmail.com"));
myRecycleAdapter.notifyItemInserted(studentList.size());
}
myRecycleAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 1000);
}
});
ItemViewHolderNew.setRecyclerListener(this);
mRecyclerView.setAdapter(myRecycleAdapter);
if (studentList.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
}
private void loadData() {
for (int i = 1; i <= 20; i++) {
studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
},5000);
}
#Override
public void onBindView(View view, final ItemViewHolderNew itemViewHolder) {
itemViewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
itemViewHolder.tvEmailId = (TextView) view.findViewById(R.id.tvEmailId);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, Object object, ItemViewHolderNew itemViewHolder) {
Student studentObj = (Student)object;
itemViewHolder.tvName.setText(studentObj.getName());
itemViewHolder.tvEmailId.setText(studentObj.getEmailId());
itemViewHolder.student= studentObj;
}
#Override
public void setClickListener(View view, ItemViewHolderNew itemViewHolder) {
Toast.makeText(view.getContext(), "OnClick :" + itemViewHolder.student.getName() + " \n " + itemViewHolder.student.getEmailId(), Toast.LENGTH_SHORT).show();
}
public static class ItemViewHolderNew extends RecyclerView.ViewHolder{
public TextView tvName, tvEmailId;
public Student student;
private static onRecyclerViewListener mListener;
public static void setRecyclerListener(onRecyclerViewListener listener){
mListener = listener;
}
public ItemViewHolderNew(View itemView) {
super(itemView);
mListener.onBindView(itemView, this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClick(v);
}
});
}
private void setClick(View v) {
mListener.setClickListener(v, this);
}
}
}
Add OnLoadMoreListener.java interface
public interface OnLoadMoreListener {
void onLoadMore();
}
Add Student.java as Model class
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String emailId;
public Student(String name, String emailId) {
this.name = name;
this.emailId = emailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No Records Here !"
android:visibility="gone" />
</RelativeLayout>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:padding="5dp"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:id="#+id/tvEmailId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
progressbar_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
</LinearLayout>
Working fine with Endless, swipe to refresh, load more RecyclerView.
Hope this would help you.
Volley RequestQueue uses a thread pool for network requests.
/** Number of network request dispatcher threads to start. */
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
Obviously, when you do fast scrolling through the list multiple requests are generated in quick succession.
There is a possibility that the responses are received asynchronously / out of sequence. Also, its possible that the "No more data" responses / error responses etc arrive before the responses with next page of data, which may lead to unexpected behaviour by your app.
Specially watch out for how this would effect your mJokes ArrayList member variable.
I am trying to build a simple chat application. With chat conversation screen I'm using ListView with ArrayAdapter to store and show the message but when I receive or send new message, all of recent message is change to.
This is my adapter code:
public class MessageAdapter extends ArrayAdapter<Message> {
private Context context;
private ArrayList<Message> messages;
private DatabaseHelper databaseHelper;
private Message message;
#Override
public void add(Message object) {
messages.add(object);
super.add(object);
}
public MessageAdapter(Context context, int textViewResouceId, ArrayList<Message> messages) {
super(context, textViewResouceId);
this.context = context;
this.messages = messages;
databaseHelper = DatabaseHelper.getInstance(context);
}
public int getCount() {
return messages.size();
}
public Message getItem(int index) {
return messages.get(index);
}
public long getItemId(int position) {
return position;
}
#Override
public int getPosition(Message item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MessageViewHolder messageViewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.chat_item, parent, false);
messageViewHolder = new MessageViewHolder();
messageViewHolder.tv_userName = (TextView) convertView.findViewById(R.id.tv_chatName);
messageViewHolder.tv_message = (TextView) convertView.findViewById(R.id.tv_messageContent);
convertView.setTag(messageViewHolder);
} else {
messageViewHolder = (MessageViewHolder) convertView.getTag();
}
message = messages.get(position);
String username = databaseHelper.getUserByUserId(message.getUserId()).getUserName();
if (message.getUserId() == AppConfig.USER_ID) {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#0066ff"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#0066ff"));
} else {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#000000"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#000000"));
}
messageViewHolder.tv_userName.setText(username);
messageViewHolder.tv_message.setText(message.getMessage());
return convertView;
}
static class MessageViewHolder {
TextView tv_message;
TextView tv_userName;
}
}
This is my ListView Layout code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ScrollView
android:id="#+id/scroll_chat"
android:layout_width="match_parent"
android:layout_height="380dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#null"
android:divider="#null"
android:stackFromBottom="true"
android:drawSelectorOnTop="false"
android:transcriptMode="alwaysScroll" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.92" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
And this is error when I send two message (the same error happen when I receive a message)
I think the problem is the way set the data to View but I cannot solve it.
Could anyone help me solve this issue.
This is chat screen when I close and open the activity again: It showed correct message.
This is Chatactivity code:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_send;
private static EditText txt_chat;
private String registId;
private Bundle bundle;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private ListView lv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
lv_message = (ListView) findViewById(R.id.listMessage);
// lv_message.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getMessges(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId());
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
}
In your ChatActivity. In onClickEvent
Try to change
Message messageObj = Message.getInstance();
to
Message messageObj = new Message();
You can read more about Singleton Pattern in here
I am using the material design tabs. I have different fragment on each tab. In one fragment I have edit Text and button and bellow is list view. ListView is populate from api and also message is create using the api(POST).
After user click on the createMessageBtn it create the message to server. But not update the listview after on click event is occur. Until Fragment Message tab not reload the newly created message not showing. When I move to different tabs and then again came to message tab then newly created message is in the listView. I want to update the listview after the createMessageBtn clicked or reload the fragment.
Here is fragment_message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/top" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create Message"
android:id="#+id/createMessagelbl"
android:textAlignment="center"
android:textStyle="bold"
android:textSize="14sp"
android:layout_marginTop="6dp"
android:gravity="center_horizontal"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/createMessagetxt"
android:layout_below="#+id/createMessagelbl"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="5dp"
android:textColor="#ff7e7e7e"
android:inputType="text" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:text="Post"
android:id="#+id/createMessagebtn"
android:layout_below="#+id/createMessagetxt"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#drawable/button"
android:layout_marginBottom="10dp"
android:layout_marginTop="1dp"
android:textColor="#ff4a8aff" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_below="#+id/top" android:padding="8dp"
android:layout_marginTop="6dp">
<ListView
android:id="#+id/messagesListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
/>
</RelativeLayout>/
</RelativeLayout>
Here Message Fragment.java
public class Message extends Fragment implements View.OnClickListener {
private ArrayList<Messages> mMessagesList = new ArrayList<>();
private MessagesListAdapter mAdapter;
ListView mListView;
EditText mMessageText;
Button mMessagePostBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMessages();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_messages, container, false);
mListView = (ListView) view.findViewById(R.id.messagesListView);
mMessageText = (EditText) view.findViewById(R.id.createMessagetxt);
mMessagePostBtn = (Button) view.findViewById(R.id.createMessagebtn);
mMessagePostBtn.setOnClickListener(this);
mAdapter = new MessagesListAdapter(getActivity().getApplicationContext(), mMessagesList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
return view;
}
private void getMessages() {
String URL ="Url";
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Here I am adding the result to mMessagesList
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.setData(mMessageList);
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}) {
// Here is my token
String token = "Token " + getToken;
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", token);
return headers;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.createMessagebtn:
if (mMessageText.getText().toString().length() == 0) {
mMessageText.setError("Please Enter the Message");
} else {
String url = "Url";
postMessage(url, mMessageText.getText().toString());
mMessageText.setText("");
getMessages();
/*FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MessagesFragment messageFragment = new MessagesFragment();
ft.detach(messageFragment);
ft.attach(messageFragment);
ft.commit();*/
}
}
}
public void postMessage(String url, final String message) {
ToastMessage.showToastMessage(getActivity().getApplicationContext(), message);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// Here Message is post Successfully
getMessages();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.getMessage());
}
}
) {
// Here is my token
String token = "Token " + getToken;
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("message", message);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<String, String>();
header.put("Authorization", token);
return header;
}
};
AppController.getInstance().addToRequestQueue(postRequest);
}
}
Here is my PageAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 5;
private String tabTitles[] = new String[] { "Some", "Some", "Some","Messages", "Some" };
private Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SomeFragment some = new SomeFragment ();
return some ;
case 1:
SomeFragment some = new SomeFragment ();
return market;
case 2:
SomeFragment some = new SomeFragment ();
return some ;
case 3:
MessagesFragment messages = new MessagesFragment();
return messages;
case 4:
SomeFragment some = new SomeFragment ();
return some ;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Here MessageListAdapter.java
public class MessagesListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Messages> messagesItems;
private LayoutInflater mInflater;
public MessagesListAdapter(Context mContext, ArrayList<Messages> messagesItems) {
this.mContext = mContext;
this.messagesItems = messagesItems;
}
public void setData(ArrayList<Messages> messagesItems) {
this.messagesItems = messagesItems;
notifyDataSetChanged();
}
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mInflater == null)
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = mInflater.inflate(R.layout.messages_list_row, null);
//here my view from xml files
Messages m = messagesItems.get(position);
//here My populate xml file with data
return convertView;
}
}