I was testing my app on many device and it was working fine...Untill I tested on an android device running android 7.1 the recycler view is gone while it exists on other devices tahte my Code:
RecyclerGridLayoutAdapter:
public class RecyclerGridLayoutAdapter extends RecyclerView.Adapter<RecyclerGridLayoutAdapter.ViewHolder>{
private int resource;
private ArrayList<Item> contacts;
private TreeMap<String,ArrayList<Contact>> gridsMap;
private String searchedString;
private Context activity;
private String myNumber;
public RecyclerGridLayoutAdapter(int resource, ArrayList<Item> contacts,Context activity) {
this.resource = resource;
this.contacts = contacts;
this.activity=activity;
gridsMap= DatabaseHandler.getDataBaseHandler(activity).getContactsByAlphabets();
loadData();
searchedString="";
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v= LayoutInflater.from(activity).inflate(resource,parent,false);
ViewHolder vh=new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
Log.wtf("begin ","inserting "+contacts.get(position).type);
if(contacts.get(position).type==0){
holder.header.setVisibility(View.VISIBLE);
holder.header.setText(contacts.get(position).alphabet);
holder.name.setVisibility(View.GONE);
holder.image.setVisibility(View.GONE);
}
else {
holder.header.setVisibility(View.GONE);
holder.name.setVisibility(View.VISIBLE);
holder.image.setVisibility(View.VISIBLE);
SharedPreferences prefs=activity.getSharedPreferences("myNumber",0);
final String myNumber=prefs.getString("number","not pund");
holder.name.setText(contacts.get(position).contact.name);
if(contacts.get(position).contact.isRegistered.equalsIgnoreCase("true")){
holder.image.setBackgroundResource(R.drawable.contact_offline_pic);
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(activity, ChatRoomActivity.class);
AppMasterManager.activity=ChatRoomActivity.class;
intent.putExtra("room",contacts.get(position).contact.room);
intent.putExtra("contact_name",contacts.get(position).contact.name);
intent.putExtra("myNumber",myNumber);
if (contacts.get(position).contact.isPrivate.equalsIgnoreCase("true")){
if (!DatabaseHandler.getDataBaseHandler(activity).numberExist(contacts.get(position).contact.phone_number)){
DatabaseHandler.getDataBaseHandler(activity).addPrivateContact(contacts.get(position).contact);
try {
ChatService.bind.getService().joinANumber(contacts.get(position).contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
intent.putExtra("account", Accounts.SECONDARY_ACCOUNT);
}else {
intent.putExtra("account", Accounts.PRIMARY_ACCOUNT);
}
Log.wtf("from grid adapter inflater",contacts.get(position).contact.room);
activity.startActivity(intent);
}
});
if(contacts.get(position).contact.state.equalsIgnoreCase("offline")){
holder.image.setBackgroundResource(R.drawable.contact_offline_pic);
}
else {
holder.image.setBackgroundResource(R.drawable.contact_online_pic);
}
}
else {
holder.image.setBackgroundResource(R.drawable.contact_unregistered_pic);
}
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView header;
public TextView name;
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
header=(TextView)itemView.findViewById(R.id.first_char_header);
name=(TextView)itemView.findViewById(R.id.contact_name);
image=(ImageView)itemView.findViewById(R.id.image_grid_contact);
}
}
#Override
public int getItemViewType(int position) {
if(contacts.get(position).type==0){
return 4;
}
else {
return 1;
}
}
public void search(String pattern){
searchedString=pattern;
if(!TextUtils.isEmpty(pattern)) {
searchedString=pattern;
gridsMap.clear();
gridsMap=DatabaseHandler.getDataBaseHandler(activity).getContactsByAlphabetsWithPattern(pattern);
contacts.clear();
loadData();
}
else {
gridsMap.clear();
gridsMap=DatabaseHandler.getDataBaseHandler(activity).getContactsByAlphabets();
contacts.clear();
loadData();
}
notifyDataSetChanged();
}
public void updateDataSet(){
if(!TextUtils.isEmpty(searchedString)){
contacts.clear();
gridsMap.clear();
gridsMap=DatabaseHandler.getDataBaseHandler(activity).getContactsByAlphabetsWithPattern(searchedString);
loadData();
notifyDataSetChanged();
}
else {
contacts.clear();
gridsMap.clear();
gridsMap=DatabaseHandler.getDataBaseHandler(activity).getContactsByAlphabets();
loadData();
notifyDataSetChanged();
}
}
void loadData(){
for(String c:gridsMap.keySet()){
contacts.add(new Item(0,c));
Log.wtf("add","+");
for(Contact d:gridsMap.get(c)){
contacts.add(new Item(1,c,d));
}}
}
public void searchOnline(final String pattern) throws JSONException {
if(!TextUtils.isEmpty(pattern)){
JSONObject object=new JSONObject();
object.put("pattern",pattern);
JsonObjectRequest request_json = new JsonObjectRequest(WebServiceApi.SEARCH_SECONDARY_CONTACTS_ONLINE,object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.getJSONArray("res").length()>0){
contacts.clear();
Log.w("result ",response.getJSONArray("res").getJSONObject(0).getJSONObject("secondary_account").getString("user_name").toString());
contacts.add(new Item(0,pattern.toCharArray()[0]+""));
for(int i=0;i<response.getJSONArray("res").length();i++){
String name=response.getJSONArray("res").getJSONObject(i).getJSONObject("secondary_account").getString("user_name");
String phone_number=response.getJSONArray("res").getJSONObject(i).getString("phone_number");
String room;
if(phone_number.compareTo(myNumber)>0){
room=phone_number+myNumber;
}
else {
room=myNumber+phone_number;
}
Contact contact=new Contact();
contact.name=name;
contact.room=room;
contact.phone_number=phone_number;
contact.isRegistered="true";
contact.state="offline";
contact.isPrivate="true";
contacts.add(new Item(1,pattern.toCharArray()[0]+"",contact));
}
notifyDataSetChanged();
}
else{
contacts.clear();
loadData();
notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("No Activity", error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request_json);
}
else {
contacts.clear();
loadData();
notifyDataSetChanged();
}
}
public void setNumber(String number){
myNumber=number;
}
}
ContactsFragement:
public class ContactsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnContactsFragementInteraction mListener;
private RecyclerView listContacts;
private GridLayoutManager manager;
private HashMap<String,Contact> roomMaps;
private String number;
private boolean isLoaded=false;
private RecyclerGridLayoutAdapter adapter;
public ContactsFragment() {
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ContactsFragment.
*/
// TODO: Rename and change types and number of parameters
public static ContactsFragment newInstance(String param1, String param2) {
ContactsFragment fragment = new ContactsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_contacts, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListener.pressed();
if(savedInstanceState==null){Toast.makeText(getActivity(),"First Time running this fragment",Toast.LENGTH_SHORT).show();}
roomMaps = new HashMap<>();
listContacts = (RecyclerView) getActivity().findViewById(R.id.list_contacts);
EditText contact_search_box = (EditText) getActivity().findViewById(R.id.search_box_contacts);
contact_search_box.clearFocus();
number = this.getArguments().getString("number");
// contactsListAdapter = new ContactsListAdapterAlternative(getActivity(), new ArrayList<GridLayoutAdapter>(), R.layout.list_contacts_item);
// listContacts.setAdapter(contactsListAdapter);
manager=new GridLayoutManager(getActivity(),4);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (adapter.getItemViewType(position));
}
});
adapter=new RecyclerGridLayoutAdapter(R.layout.list_contacts_item,new ArrayList<Item>(),getActivity());
adapter.setNumber(number);
manager.setOrientation(LinearLayoutManager.VERTICAL);
listContacts.setLayoutManager(manager);
listContacts.setHasFixedSize(true);
listContacts.setAdapter(adapter);
EditText search_online_box=getActivity().findViewById(R.id.search_online);
search_online_box.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
adapter.searchOnline(s.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
contact_search_box.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
adapter.search(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
isLoaded=true;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnContactsFragementInteraction) {
mListener = (OnContactsFragementInteraction) context;
mListener.pressed();
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void updateState(String room,HashMap<String,String> map) {
if(adapter!=null)
adapter.updateDataSet();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnContactsFragementInteraction {
// TODO: Update argument type and name
void pressed();
ChatService getService();
void setRoutablity(boolean routablity);
}
}
fragment_contacts:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/contactsFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"
android:id="#+id/topSearchBar"
android:weightSum="2">
<EditText
android:id="#+id/search_box_contacts"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="10dp"
android:textSize="15sp"
android:hint="search contacts"
android:background="#beddeb"/>
<EditText
android:id="#+id/search_online"
android:layout_width="0dp"
android:layout_height="match_parent"
android:hint="search online"
android:padding="10dp"
android:textSize="15sp"
android:background="#5fc0e9"
android:layout_weight="1"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/list_contacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/topSearchBar"
android:scrollbars="vertical"
tools:listitem="#layout/list_contacts_item">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_contact_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/first_char_header"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="a"
android:paddingTop="6dp"
android:paddingLeft="8dp"
android:textSize="25sp"
android:textColor="#c1292f"
android:background="#f2f2f2"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:lines="2"
android:id="#+id/contact_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Abdallah"
android:padding="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:src="#drawable/contact_small"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/image_grid_contact"
android:background="#drawable/contact_offline_pic"/>
</LinearLayout>
</LinearLayout>
This gridView is simply a contacts grid where it shows all the contacts available and registered in my network...
On log it shows that it recognizes that there are registered contacts and even it receives a message and if I open the chats tab i see that this listview contact send a message though no contact is appearing in the recycler view...
Related
I'm building a RecyclerView in a Fragment, which brings in data from Firebase database and suppose to show them on a CardView. I wrote all the code as shown below but all that appears upon running is an empty RecyclerView Fragment with the method getItemCount() returning always 0.
card_item.xml
<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:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="10dp"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<TextView
android:id="#+id/primaryText"
android:layout_width="300dp"
android:layout_height="60dp"
android:textColor="#color/colorPrimary"
android:textSize="24sp" />
<TextView
android:id="#+id/subText"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"
android:textSize="14sp" />
<TextView
android:id="#+id/rateValue"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/subText"
android:textColor="#color/colorPrimary"
android:textSize="24sp" />
</RelativeLayout>
fragment_profile.xml
<LinearLayout 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:background="#F1F1F1"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/placesRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
PlacesModel.java
public class PlaceModel {
private String mPrimaryText, mSubText, mRateValue;
public PlaceModel() {
}
public PlaceModel(String mCardImage, String mPrimaryText,
String mSubText, String mRateValue) {
//this.mCardImageURL = mCardImage;
this.mPrimaryText = mPrimaryText;
this.mSubText = mSubText;
this.mRateValue = mRateValue;
}
public void setmPrimaryText(String mPrimaryText) {
this.mPrimaryText = mPrimaryText;
}
public void setmSubText(String mSubText) {
this.mSubText = mSubText;
}
public void setmRateValue(String mRateValue) {
this.mRateValue = mRateValue;
}
public String getmPrimaryText() {
return mPrimaryText;
}
public String getmSubText() {
return mSubText;
}
public String getmRateValue() {
return mRateValue;
}}
PlacesAdapter.java
public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.PlacesViewHolder> {
private ArrayList<PlaceModel> cardContents;
private Context context;
public PlacesAdapter(Context context, ArrayList<PlaceModel> cardContents) {
this.cardContents = cardContents;
this.context = context;
}
#Override
public PlacesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false);
return new PlacesViewHolder(view);
}
#Override
public void onBindViewHolder(PlacesViewHolder holder, int position) {
PlaceModel place = cardContents.get(position);
holder.primaryText.setText(place.getmPrimaryText());
holder.subText.setText(place.getmSubText());
holder.rateValue.setText(place.getmRateValue());
}
#Override
public int getItemCount() {
return cardContents.size();
}
public class PlacesViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
public TextView primaryText, subText, rateValue;
public PlacesViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardView);
primaryText = (TextView) itemView.findViewById(R.id.primaryText);
subText = (TextView) itemView.findViewById(R.id.subText);
rateValue = (TextView) itemView.findViewById(R.id.rateValue);
}
}}
FirebaseConnector.java
public class FirebaseConnector {
DatabaseReference db;
PlaceModel placeModel = new PlaceModel();
ArrayList<PlaceModel> cardContent = new ArrayList<>();
public FirebaseConnector(DatabaseReference db) {
this.db = db;
}
public ArrayList<PlaceModel> retrieve() {
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return cardContent;
}
private void fetchData(DataSnapshot dataSnapshot) {
cardContent.clear(); //clear card content from last usage
for (DataSnapshot ds : dataSnapshot.getChildren()) {
placeModel = ds.child("Place Model").getValue(PlaceModel.class);
cardContent.add(placeModel);
}
}}
ProfileFragment.java
public class ProfileFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
/////////////////////////////////////////////////////////////
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private RecyclerView placesRecycler;
private PlacesAdapter placesAdapter;
private FirebaseConnector connector;
private DatabaseReference ref;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
mAuth = FirebaseAuth.getInstance();
//Initialize Database..
ref = FirebaseDatabase.getInstance().getReference();
connector = new FirebaseConnector(ref);
//Initialize RecyclerView
placesRecycler = (RecyclerView)v.findViewById(R.id.placesRecycler);
placesRecycler.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//Adapter
placesAdapter = new PlacesAdapter(this.getActivity(), connector.retrieve());
placesRecycler.setAdapter(placesAdapter);
Toast.makeText(getActivity(), "We have "+placesAdapter.getItemCount()+" cards", Toast.LENGTH_LONG).show();
return v;
}
#Override
public void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
}
public void updateUI() {
if (mAuth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
}}
Database trial structure
Database trial structure
I see that retrieve method will return empty array list because it won't wait for the listener to finish (note that listener works in another thread)
You may make move the listener to the profile fragment and every time you update the ArrayList write
placesRecycler.notifydatasetchanged();
I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
// #Override
//public CharSequence getPageTitle(int position) {
//return data.get(position).getName();
// }
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
ImageView ImageView;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
//private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
//this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
//args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"
Recyclerview doesnt call any Adapter method :onBindViewHolder,onCreateViewHolder therefor the adapter is empty
here is my code :
public class PostsFragment extends Fragment {
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private static final String KEY_TYPE = "type";
public static final int TYPE_HOME = 1001;
public static final int TYPE_FEED = 1002;
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance(int type) {
PostsFragment fragment = new PostsFragment();
Bundle args = new Bundle();
args.putInt(KEY_TYPE, type);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
if (savedInstanceState != null) {
// Restore saved layout manager type.
mRecyclerViewPosition = (int) savedInstanceState
.getSerializable(KEY_LAYOUT_POSITION);
mRecyclerView.scrollToPosition(mRecyclerViewPosition);
// TODO: RecyclerView only restores position properly for some tabs.
}
switch (getArguments().getInt(KEY_TYPE)) {
case TYPE_HOME:
Log.d(TAG, "Restoring recycler view position (following): " + mRecyclerViewPosition);
FirebaseUtil.getCurrentUserRef().child("following").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot followedUserSnapshot, String s) {
String followedUserId = followedUserSnapshot.getKey();
String lastKey = "";
if (followedUserSnapshot.getValue() instanceof String) {
lastKey = followedUserSnapshot.getValue().toString();
}
Log.d(TAG, "followed user id: " + followedUserId);
Log.d(TAG, "last key: " + lastKey);
FirebaseUtil.getPeopleRef().child(followedUserId).child("posts")
.orderByKey().startAt(lastKey).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot postSnapshot, String s) {
HashMap<String, Object> addedPost = new HashMap<String, Object>();
addedPost.put(postSnapshot.getKey(), true);
FirebaseUtil.getFeedRef().child(FirebaseUtil.getCurrentUserId())
.updateChildren(addedPost).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
FirebaseUtil.getCurrentUserRef().child("following")
.child(followedUserSnapshot.getKey())
.setValue(postSnapshot.getKey());
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
FirebaseUtil.getFeedRef().child(FirebaseUtil.getCurrentUserId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> postPaths = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "adding post key: " + snapshot.getKey());
postPaths.add(snapshot.getKey());
}
mAdapter = new FirebasePostQueryAdapter(postPaths,
new FirebasePostQueryAdapter.OnSetupViewListener() {
#Override
public void onSetupView(PostViewHolder holder, Post post, int position, String postKey) {
setupPost(holder, post, position, postKey);
}
});
}
#Override
public void onCancelled(DatabaseError firebaseError) {
}
});
break;
default:
throw new RuntimeException("Illegal post fragment type specified.");
}
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
*/
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
the adapter class
public class FirebasePostQueryAdapter extends RecyclerView.Adapter<PostViewHolder> {
private final String TAG = "PostQueryAdapter";
private List<String> mPostPaths;
private OnSetupViewListener mOnSetupViewListener;
public FirebasePostQueryAdapter(List<String> paths, OnSetupViewListener onSetupViewListener) {
if (paths == null || paths.isEmpty()) {
mPostPaths = new ArrayList<>();
} else {
mPostPaths = paths;
}
mOnSetupViewListener = onSetupViewListener;
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_item, parent, false);
return new PostViewHolder(v);
}
public void setPaths(List<String> postPaths) {
mPostPaths = postPaths;
notifyDataSetChanged();
}
public void addItem(String path) {
mPostPaths.add(path);
notifyItemInserted(mPostPaths.size());
}
#Override
public void onBindViewHolder(final PostViewHolder holder, int position) {
DatabaseReference ref = FirebaseUtil.getPostsRef().child(mPostPaths.get(position));
// TODO: Fix this so async event won't bind the wrong view post recycle.
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
Log.d(TAG, "post key: " + dataSnapshot.getKey());
mOnSetupViewListener.onSetupView(holder, post, holder.getAdapterPosition(),
dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError firebaseError) {
Log.e(TAG, "Error occurred: " + firebaseError.getMessage());
}
};
ref.addValueEventListener(postListener);
holder.mPostRef = ref;
holder.mPostListener = postListener;
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
holder.mPostRef.removeEventListener(holder.mPostListener);
}
#Override
public int getItemCount() {
return mPostPaths.size();
}
public interface OnSetupViewListener {
void onSetupView(PostViewHolder holder, Post post, int position, String postKey);
}
}
the main class
public class FeedsActivity extends AppCompatActivity implements PostsFragment.OnPostSelectedListener {
private static final String TAG = "FeedsActivity";
private FloatingActionButton mFab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeds);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.feeds_view_pager);
FeedsPagerAdapter adapter = new FeedsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(PostsFragment.newInstance(PostsFragment.TYPE_HOME), "HOME");
adapter.addFragment(PostsFragment.newInstance(PostsFragment.TYPE_FEED), "FEED");
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
TabLayout tabLayout = (TabLayout) findViewById(R.id.feeds_tab_layout);
tabLayout.setupWithViewPager(viewPager);
mFab = (FloatingActionButton) findViewById(R.id.fab);
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null || user.isAnonymous()) {
Toast.makeText(FeedsActivity.this, "You must sign-in to post.", Toast.LENGTH_SHORT).show();
return;
}
Intent newPostIntent = new Intent(FeedsActivity.this, NewPostActivity.class);
startActivity(newPostIntent);
}
});
}
#Override
public void onPostComment(String postKey) {
Intent intent = new Intent(this, CommentsActivity.class);
intent.putExtra(CommentsActivity.POST_KEY_EXTRA, postKey);
startActivity(intent);
}
#Override
public void onPostLike(final String postKey) {
final String userKey = FirebaseUtil.getCurrentUserId();
final DatabaseReference postLikesRef = FirebaseUtil.getLikesRef();
postLikesRef.child(postKey).child(userKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User already liked this post, so we toggle like off.
postLikesRef.child(postKey).child(userKey).removeValue();
} else {
postLikesRef.child(postKey).child(userKey).setValue(ServerValue.TIMESTAMP);
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_feeds, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// TODO: Add settings screen.
return true;
} else if (id == R.id.action_profile) {
startActivity(new Intent(this, ProfileActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
class FeedsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public FeedsPagerAdapter(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);
}
}
}
activity_feeds.xml
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<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.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.TabLayout
android:id="#+id/feeds_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/feeds_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add"
android:tint="#android:color/white"/>
post_item.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/post_author_icon"
android:layout_width="#dimen/post_author_icon_size"
android:layout_height="#dimen/post_author_icon_size"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/post_author_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/post_author_icon"
android:layout_marginLeft="4dp"
style="#style/Base.TextAppearance.AppCompat.Title"
android:textColor="#android:color/primary_text_light_nodisable"
android:text="Unknown"/>
<TextView
android:id="#+id/post_timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_gravity="end"
android:textColor="#android:color/primary_text_light"
android:textSize="18sp" />
</RelativeLayout>
<ImageView
android:id="#+id/post_photo"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="false"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp"
android:textColor="#android:color/primary_text_light"
android:textSize="16sp"
android:ellipsize="end" />
<TextView
android:id="#+id/post_num_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp"
android:textColor="#android:color/secondary_text_light"
android:textSize="14sp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp">
<ImageView
android:id="#+id/post_like_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/heart_full"/>
<ImageView
android:id="#+id/post_comment_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="6dp"
android:layout_toRightOf="#id/post_like_icon"
android:src="#drawable/ic_chat_24dp"
android:tint="#color/blue_grey_500"/>
</RelativeLayout>
</LinearLayout>
fragment_posts.xml
<FrameLayout 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"
tools:context=".PostsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
You are setting the adapter on the recyclerview before the adapter has been initialised. Try:
mAdapter = new FirebasePostQueryAdapter(postPaths,
new FirebasePostQueryAdapter.OnSetupViewListener() {
#Override
public void onSetupView(PostViewHolder holder, Post post, int position, String postKey) {
setupPost(holder, post, position, postKey);
}
});
mRecyclerView.setAdapter(mAdapter);
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 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;
}
}