Click on tab itemes response from next tab items - android-fragments

I have a fragment with fragment pager adapter implements tablayout...each tab has a recycler view with some items(same recyler view adapter for all recylerviews)... by implementing OnItemClick listener for click on each item call an activity that implement a viewpager with fragmentStatePagerAdapter,to shows recycler view items...based on swipe of tablayout viewpager shows previous or next tab items...
data of each item stores in a arraylist.
when i'm clcking on one item in current tab it likes i'm clicking on next tab item in a same position
tablayput fragment:
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
//setupViewPager(viewPager);
MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getChildFragmentManager(),getActivity());
adapter.addFrag(new OneFragment(), "title1");
adapter.addFrag(new TwoFragment(), "title2");
adapter.addFrag(new ThreeFragment(), "title3");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
OneFragment and TwoFragment and ... are similar:
rv=(RecyclerView) view.findViewById(R.id.rv);
StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
rv.setLayoutManager(sglm);
rv.setHasFixedSize(true);
persons = new ArrayList<>();
persons.add(new Person("name", "age","email","phone","resume", R.drawable.photo));
persons.add(new Person("name", "age","email","phone","resume", R.drawable.photo));
.
.
.
for (int j=0; j < persons.size() ;j++){
PersonItem personItem = new PersonItem();
personItem.setName(persons.get(j).name);
personItem.setAge(persons.get(j).age);
personItem.setEmail(persons.get(j).email);
personItem.setPhone(persons.get(j).phone);
personItem.setResume(persons.get(j).resume);
personItem.setImageId(persons.get(j).photoId);
personList1.addItem(personItem);
RVAdapter adapter = new RVAdapter(getContext(),persons);
adapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
int pos = position;
Bundle bundle = new Bundle();
bundle.putSerializable("person", personList1);
Intent intent = new Intent(getContext(),
MyActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);
}
});
rv.setAdapter(adapter);
recycler view adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private Context mContext;
private static OnItemClickListener listener;
//AdapterView.OnItemClickListener listener;
// Define the listener interface
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
TextView personAge;
ImageView personPhoto;
PersonViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
personName = (TextView)itemView.findViewById(R.id.person_name);
personAge = (TextView)itemView.findViewById(R.id.person_age);
personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
// Setup the click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Triggers click upwards to the adapter on click
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
}
List<Person> persons;
public RVAdapter(Context context , List<Person> persons){
this.persons = persons;
mContext = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.personName.setText(persons.get(i).name);
personViewHolder.personAge.setText(persons.get(i).age);
personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
}
#Override
public int getItemCount() {
return persons.size();
}
}

for solving this problem i've made my RvAdapter class as a inner and private class in each tab fragments :
private static class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
//...and keep remaning

Related

send data from popup to tabbed activity having fragments

mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}

How to pass retrofit data in bundle to view pager fragments from activity?

In my activity i am receiving a game id from previous activity and using this id i am getting list of data from api. The method ("ApiCheats") in activity is used to get lis t of data.
I want to pass this list to my fragment in view pager, for this i used bundle but in fragment the bundle is null.
How should i pass bundle list to fragment , this data i am receiving through retrofit.
This is the Activity
public class GameListCheatsActivity extends AppCompatActivity {
private final String TAG = GameListCheatsActivity.class.getSimpleName();
public List<Cheats> Cheats;
ArrayList cheats = new ArrayList<Cheats>();
// public RecyclerView recyclerView;
String Gameid;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list_cheats);
// recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setHasFixedSize(true);
Gameid = getIntent().getStringExtra("GameID");
tabLayout = (TabLayout) findViewById(R.id.tab_layout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter( getSupportFragmentManager());
ApiCheats();
adapter.AddFragment(new Fragment_Cheats(),"GameCheats");
adapter.AddFragment(new Fragment_Favourites(),"Favourites");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == 0){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
if(state == 1){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
}
});
}
public void ApiCheats()
{
ApiUtil.getServiceClass().getAllCheats(Gameid).enqueue(new Callback<List<Cheats>>() {
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("cheatslist", (ArrayList<? extends Parcelable>) Cheats);
Fragment_Cheats fragment_cheats = new Fragment_Cheats();
fragment_cheats.setArguments(bundle);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
#Override
public void onFailure(Call<List<Cheats>> call, Throwable t) {
Log.d(TAG, "error loading from API");
}
});
}
}
this is one of the fragments class
public class Fragment_Cheats extends Fragment {
View v;
private RecyclerView mrecyclerview;
private List<Cheats> lstGameCheats;
public Fragment_Cheats()
{
}
// #Override
// public void onCreate(#Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// lstGameCheats = bundle.getParcelable("cheatslist");
// }
//
// }
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_fragment__cheats, container, false);
mrecyclerview = (RecyclerView)v.findViewById(R.id.recyclerview_cheats);
Bundle bundle = this.getArguments();
if (bundle != null) {
lstGameCheats = bundle.getParcelable("cheatslist");
}
CheatsAdapter recyclerAdapter = new CheatsAdapter(getContext(),lstGameCheats);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerview.setAdapter(recyclerAdapter);
return v;
}
}
this is view pager adapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
//return null;
}
#Override
public int getCount() {
return lstTitles.size();
//return 0;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment,String title){
lstFragment.add(fragment);
lstTitles.add(title);
}
}
You should set the Cheats to the Fragment which have added to your ViewPagerAdater, but according to your code you just set the data to a new fragment instance.
According to the Fragment_Cheats code, if you want to invoke getArgument() in onCreate() method, you should invoke fragment.setArgument() before the fragment add to the ViewPagerAdapter.
But in your situation it is not possible, because the data get from the network.
So, two step
Set data to the correct Fragment_Cheats instance
Notify Fragment_Cheats data changed, refresh the View state in the fragment
Replace your onResponse()
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Fragment_Cheats fragment_cheats = adapter.getCheatFragment()
fragment_cheats.setDatas(Cheats);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
Fragment_Cheats add setDatas() method
public void setDatas(List<Cheats> datas) {
this.lstGameCheats = datas;
// and set the datas to the RecylerView adapter
recyclerviewAdapter.notifyDataSetChanged();
}

How to Delete a row in a RecyclerView Programmatically

Hey guys I have a recyclerview adapter that populates list of some data on a cardview. I created a three dot menu towards the lower right bottom of the card layout which would actually delete the card row from the recyclerview and also make delete of the item from the sqlite database that stores rows data. The issue is I couldn't figure out how to integrate the method that would implement the delete into the recyclerview ViewHolder. Here is the source code
public class BeneficiaryRecyclerAdapter extends RecyclerView.Adapter<BeneficiaryRecyclerAdapter.BeneficiaryViewHolder> {
private List<Beneficiary> listBeneficiary;
public ImageView overflow;
private Context mContext;
public BeneficiaryRecyclerAdapter(){
}
public BeneficiaryRecyclerAdapter(List<Beneficiary> listBeneficiary, Context mContext) {
this.listBeneficiary = listBeneficiary;
this.mContext = mContext;
}
#Override
public BeneficiaryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// inflating recycler item view
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_beneficiary_recycler, parent, false);
return new BeneficiaryViewHolder(itemView);
}
#Override
public void onBindViewHolder(final BeneficiaryViewHolder holder, int position) {
holder.textViewName.setText(listBeneficiary.get(position).getName());
holder.textViewEmail.setText(listBeneficiary.get(position).getEmail());
holder.textViewAddress.setText(listBeneficiary.get(position).getAddress());
holder.textViewCountry.setText(listBeneficiary.get(position).getAddress());
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(this.mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.beneficiary_m, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
//NOTE: The method that would delete the item from the database and recyclerview but i need this method to be called from the onMenuItemClick of the case with id of case R.id.action_delete_beneficiary
public void deleteItem(final BeneficiaryViewHolder holder, int position) {
final DatabaseHelper2 db = new DatabaseHelper2(mContext);
db.open();
db.deleteContact(position);
db.close();
listBeneficiary.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, listBeneficiary.size());
holder.itemView.setVisibility(View.GONE);
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete_beneficiary:
Toast.makeText(mContext, "deleting beneficiary", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_edit_beneficiary:
Toast.makeText(mContext, "editing beneficiary", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
Log.v(BeneficiaryRecyclerAdapter.class.getSimpleName(),""+listBeneficiary.size());
return listBeneficiary.size();
}
/**
* ViewHolder class
*/
public class BeneficiaryViewHolder extends RecyclerView.ViewHolder {
public AppCompatTextView textViewName;
public AppCompatTextView textViewEmail;
public AppCompatTextView textViewAddress;
public AppCompatTextView textViewCountry;
public ImageView overflow;
public BeneficiaryViewHolder(View view) {
super(view);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewEmail = (AppCompatTextView) view.findViewById(R.id.textViewEmail);
textViewAddress = (AppCompatTextView) view.findViewById(R.id.textViewAddress);
textViewCountry = (AppCompatTextView) view.findViewById(R.id.textViewCountry);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
}
I would be glad if anybody can help me with this.
Use this code to delete recyclerview items on same row click button.
holder.deleteImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(list.size()!=0){
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,list.size());
}
}
});

how to open a new fragment using RecyclerView

I am trying to make an app that which is like a place picker, meaning you write down a product like pizza or burger, and u get all the places around you that have pizza or burger.
now I'm using RecyclerView in my fragment and i also have Map fragment
when you click on an item in the RV, it will show its location on the map using the map fragment.
my problem is when I'm clicking on an item in the recyclerview i get nullpointerexception
here is my code of the first fragment
public class PlacesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> , AdapterView.OnItemClickListener{
ClickListener listener;
static Places places;
PlacesAdapter adapter;
public FragmentManager fm;
MyMapFragment mapFragment;
Cursor cursor;
public PlacesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myFragView= inflater.inflate(R.layout.fragment_places, container, false);
RecyclerView rv= (RecyclerView)myFragView.findViewById(R.id.placesRecyclerView);
//this create the line beetween every list to do so i have import to the build gradle a flexible divider
rv.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
cursor = getActivity().getContentResolver().query(CONTENT_URI, null, null, null, null);
adapter= new PlacesAdapter(cursor, getActivity());
rv.setAdapter(adapter);
adapter.notifyItemRangeChanged(cursor.getPosition(), cursor.getCount());
adapter.notifyDataSetChanged();
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
rv.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rv, new ClickListener() {
#Override
public void onPlaceClick(String latlng) {
//when i click on a place it will go to the map fragment
// Toast.makeText(getActivity(), "on click" + position, Toast.LENGTH_LONG).show();
/* FragmentManager fm = getFragmentManager();
// get the map object from the fragment:
mapFragment = MyMapFragment.newInstance(places);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragmantContainer, mapFragment, "map");
ft.addToBackStack(null);
ft.commit();*/
}
})
);
// getLoaderManager().initLoader(1, null,);
return myFragView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (ClickListener)context;
} catch (ClassCastException e) {
throw new ClassCastException("context " + context.toString()
+ "must implement PlacesFragmantListener!");
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// CursorLoader c=getContext().getContentResolver().query(PlacesContract.Places.CONTENT_URI, null, null,null, null);
return new CursorLoader(getActivity(),CONTENT_URI, null, null,null, null );
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public static interface PlacesFragmantListener {
public void onLocationSelected(Places places);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
MyMapFragment mapFragment;
public RecyclerTouchListener(Context context, RecyclerView recyclerView, ClickListener clickListener){
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
});
this.clickListener = clickListener;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("PlaceAdapter", "onTouchEvent"+e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
here is my map fragment
public class MyMapFragment extends Fragment {
public MyMapFragment(){
}
public static MyMapFragment newInstance(Places places) {}
if (places == null) {
places = new Places(0,"no Location selected","","", "");
}
// the arguments to pass
Bundle args = new Bundle();
args.putString("location", places.getLocation());
args.putDouble("lat", location.getLat());
args.putDouble("lon", location.getLon());
MyMapFragment mapFragmant = new MyMapFragment();
mapFragmant.setArguments(args);
return mapFragmant;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mapfragment, container, false);
Bundle b=getArguments();
String latlng= b.getString("location");
Log.d("fragment...", latlng);
String[] latlongarr= latlng.split(",");
double lat= Double.parseDouble(latlongarr[0]);
double lon= Double.parseDouble(latlongarr[1]);
FragmentManager fm = getFragmentManager();
MapFragment mapFragment = (MapFragment) fm.findFragmentById(R.id.map);
// get the map object from the fragment:
GoogleMap map = mapFragment.getMap();
if(map!= null) {
// setup the map type:
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// setup map position and zoom
LatLng position = new LatLng(b.getDouble("lat"), b.getDouble("lon"));
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(position, 15);
map.moveCamera(update);
}
return view;
}
}
here is my adapter
public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.PlaceHolder> {
private Cursor cursor;
private Context context;
private static TextView placeName, address, distance, url;
public static ImageView imgplace;
public static PlaceHolder.ClickListener clickListener;
private static Places place;
private DataSetObserver mDataSetObserver;
MyMapFragment mapFragment;
private boolean mDataValid;
ClickListener listener;
public PlacesAdapter(Cursor cursor, Context context) {
this.context = context;
this.cursor = cursor;
mDataSetObserver = new NotifyingDataSetObserver();
if (cursor != null) {
cursor.registerDataSetObserver(mDataSetObserver);
}
}
#Override
public PlaceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// cursor.setNotificationUri(context.getContentResolver(), CONTENT_URI);
LayoutInflater inflater = LayoutInflater.from(context);
View myView = inflater.inflate(R.layout.single_place, parent, false);
PlaceHolder placeHolder = new PlaceHolder(myView, new PlaceHolder.PlacesFragmantListener() {
#Override
public void onLocationSelected(Places places) {
}
});
return placeHolder;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(true);
}
#Override
public void onBindViewHolder(PlacesAdapter.PlaceHolder holder, final int position) {
if (cursor.moveToPosition(position)) {
int column_number = cursor.getColumnIndex(PLACES_NAME);
String name = cursor.getString(column_number);
placeName.setText(name);
int column_number2 = cursor.getColumnIndex(PLACES_ADDRESS);
String adr = cursor.getString(column_number2);
address.setText(adr);
int column_number3 = cursor.getColumnIndex(PLACES_DISTANEC);
String dis = cursor.getString(column_number3);
distance.setText(dis);
int column_number4 = cursor.getColumnIndex(PLACE_PHOTO);
String photo = cursor.getString(column_number4);
if(!photo.equals(""))
{
GoogleAccess.myImageDownloader loader= new GoogleAccess.myImageDownloader(imgplace);
loader.execute(photo);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Item click at " + position, Toast.LENGTH_LONG).show();
if(cursor.moveToPosition(position))
{
String latlong= cursor.getString(cursor.getColumnIndex(PlacesDbconstanst.CurrentPlaces.PLACES_DISTANEC));
listener.onPlaceClick(latlong);
}
}
});
}
public void setClickListener(PlaceHolder.ClickListener clickListener){
this.clickListener = clickListener;
}
#Override
public int getItemCount() {
return cursor.getCount();
}
public static class PlaceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesFragmantListener listener;
public PlaceHolder(View itemView, PlacesFragmantListener placesFragmantListener) {
super(itemView);
listener = placesFragmantListener;
placeName = (TextView) itemView.findViewById(R.id.placeNametextView);
address = (TextView) itemView.findViewById(R.id.addressTextView);
distance = (TextView) itemView.findViewById(R.id.distanceTextView);
imgplace = (ImageView) itemView.findViewById(R.id.placesImageViewId);
imgplace.setOnClickListener(this);
itemView.setOnClickListener(this);
}
RecyclerView rv;
#Override
public void onClick(View v) {
if(clickListener!=null){
clickListener.itemClicked(v, getPosition());
}
}
public static interface PlacesFragmantListener {
void onLocationSelected(Places places);
}
public interface ClickListener{
public void itemClicked (View view, int position);
}
}
private class NotifyingDataSetObserver extends DataSetObserver {
#Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
}
}
}
can you tell me what i did wrong
here is the log comment
03-30 04:55:28.042 2318-2318/com.myapps.pinkas.placesofintrest W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4c8cb20)
03-30 04:55:28.042 2318-2318/com.myapps.pinkas.placesofintrest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapps.pinkas.placesofintrest, PID: 2318
java.lang.NullPointerException
at com.myapps.pinkas.placesofintrest.PlacesAdapter$2.onClick(PlacesAdapter.java:112)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
distance = (TextView) itemView.findViewById(R.id.distanceTextView);
is this line come in 112 in your class file, it's seems like, you have not defined view id or view in XML, please check line number 112 in PlacesAdapter.class
Problem 1: Setting onclick listener twice. In onbindviewholder you have put holder.itemView.setOnclicklistener and then again in static class viewholder, you have put itemview.setOnclickListener. When you assign setOnclicklistener inside the static viewholder class, it means it will behave in a particular way uninfluenced by values present in any other views (like textview, imageview) or any such factors which depend on some 'value' property of the views. For most purposes you should have setOnClicklistener onto the itemview/textview/etc inside the static viewholder class which in your case is called placeholder.
Problem 2: Here is the reason why I believe you are getting NullPointerException. onbindviewholder has access to only the views declared in static viewholder class. If you want itemview to be accessible to onbindviewholder then make the following changes:
public static class PlaceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesFragmantListener listener;
View iv;
public PlaceHolder(View itemView, PlacesFragmantListener placesFragmantListener) {
super(itemView);
iv = (View)itemView;
//then rest of the code
Now in your onbindviewholder write the following instead of holder.itemview.setonclicklistener
holder.iv.setonclicklistener...
Problem 3: in your static viewholder, you have put:
imgplace.setOnClickListener(this);
itemView.setOnClickListener(this);
itemview is the layout in which imgplace exists. And you have setonclicklistener on both of them. This is like putting a button on a button. It makes no sense. I think this will lead you into lot of mess. For some reason you want both to perform the same function on being clicked (you have put 'this' inside setOnClickListener). This is completely illogical. So set the clicklistener to either imgplace or itemview but not both

How to load Different adapters on same listview on Button Click-[Android]?

My requirement is to load different adapters on same listview using buttons to switch between adapters.
I've tried this
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String flo[] = {"Rose","Lily","SunFlower","Lotus","Tulips"};
String foo[] = {"Maggie","Manchurian","Pizza","Burger","French Fries"};
String cit[] = {"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
String an[] = {"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton2);
fl = (ImageButton)findViewById(R.id.imageButton);
ci = (ImageButton)findViewById(R.id.imageButton3);
ani = (ImageButton)findViewById(R.id.imageButton4);
l =(ListView)findViewById(R.id.listView);
fo.setOnClickListener(this);
fl.setOnClickListener(this);
ci.setOnClickListener(this);
ani.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton2)
{
food f = new food(this,foo);
l.setAdapter(f);
}
}
}
And I'm getting the following Error:
FATAL EXCEPTION: main
Process: com.example.nike.assignmentadapter, PID: 2565
java.lang.NullPointerException: Attempt to get length of null array
at com.example.nike.assignmentadapter.food.getCount(food.java:41)
at android.widget.ListView.setAdapter(ListView.java:487)
at com.example.nike.assignmentadapter.MainActivity.onClick(MainActivity.java:74)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Food class
public class food extends BaseAdapter implements View.OnClickListener {
String s[];
Context c;
Button li;
Button sh ;
int a[] = {R.drawable.fl1,R.drawable.fl2,R.drawable.fl3,R.drawable.fl4,R.drawable.fl5};
public food(Context context, String[] xperia) {
s = xperia;
c = context;
}
#Override
public int getCount() {
return s.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return s.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater ln = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = ln.inflate(R.layout.food, null);
TextView t= (TextView)v.findViewById(R.id.textView4);
ImageView i = (ImageView)v.findViewById(R.id.imageView4);
li = (Button)v.findViewById(R.id.like4);
sh = (Button)v.findViewById(R.id.share4);
String s1=s[position];
t.setText(s1);
i.setImageResource(a[position]);
li.setOnClickListener(this);
sh.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.like4)
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Liking ");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Share", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("http://www.sonymobile.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
else
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Sharing on Your Facebook");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Facebook", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("https://www.facebook.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
}
}
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
// these are your global variables available to access
// in any part of the coding. Currently they have no
// data assigned to them in other words they are null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// here we have assigned data to the global variables declared
// outside of the OnCreate function and available to the onClick
// call.
// Using String flo[] = {John, Doe} means you are creating
// new local versions of the String arrays that are not available
// globally. Instead of assigning the data to the variables
// available globally, and to the onClick call, the data is given
// to the local variables only accessible in the OnCreate function
// function and available until OnCreate finishes.
flo = new String[]{"Rose","Lily","SunFlower","Lotus","Tulips"};
foo = new String[]{"Maggie","Manchurian","Pizza","Burger","French Fries"};
cit = new String[]{"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
an = new String[]{"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton1);
l =(ListView)findViewById(R.id.listView1);
fo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton1)
{
System.out.println("foo: " + foo);
food f = new food(this,foo);
l.setAdapter(f);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Resources