Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] java – How do I extablish context for an Activity within a recyclerview adapter

Posted on November 11, 2022 By

Solution 1 :

In the constructor of CheckInListAdapter pass another argument as context

public CheckInListAdapter(int layoutId, Context context) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
        this.context = context
    }

Problem :

I have buttons within the rows of a recyclerview within a fragment within an activity. When the user clicks one of the buttons, I want to switch to a different activity. How do I establish context for the Intent to switch to the new activity.

OR, should I move the onClickListener back to the fragment or activity (is it incorrect to place onClickListener within the recyclerview adapter code). If so, how do I obtain reference to the button clicked from outside the recyclerview adapter.

Here is the fragment code (CheckInRecentList.java)

package com.example.checkingin;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;

import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;



import com.google.android.material.snackbar.Snackbar;

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link CheckInRecentList.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link CheckInRecentList#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CheckInRecentList 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 RecyclerView recyclerView;
    private RecyclerView.Adapter checkInListAdapter;
    //private RecyclerView.LayoutManager layoutManager;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private MainViewModel mViewModel;
    private CheckInListAdapter mAdapter;
    private MainViewModelProviderFactory viewModelFactory;
    private TextView checkInLastDateTime;
    private TextView checkInTitle;
    private TextView checkInDestinationName;
    private TextView checkInComments;
    private Context context;

    private OnFragmentInteractionListener mListener;

    public CheckInRecentList() {
        // Required empty public constructor
    }

    /**
     * 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 CheckInRecentList.
     */
    // TODO: Rename and change types and number of parameters
    public static CheckInRecentList newInstance(String param1, String param2) {
        CheckInRecentList fragment = new CheckInRecentList();
        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);
        Log.i(TAG, "onCreate: On Create");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

            }

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
       Log.i(TAG, "onCreateView: On Create View"); 
       // Inflate the layout for this fragment
              return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);



    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        Log.i(TAG, "onButtonPressed: ");
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {

        super.onAttach(context);

        Log.i(TAG, "onAttach: OnAttach");

        viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
        mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
       Log.i(TAG,"OnAttach completed");
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);

       Log.i(TAG, "onActivityCreated: On Activity Created");


       mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);

       mAdapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
       RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
       recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
       recyclerView.setAdapter(mAdapter);
       recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
               LinearLayoutManager.VERTICAL));

        observerSetup();
        Log.i(TAG, "onActivityCreated: Observer SetUp");

        ItemTouchHelper.SimpleCallback callback = new
            ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {


                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

                    int position = viewHolder.getAdapterPosition();

                    mAdapter.deleteItem(position);
                    Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item " + (direction == ItemTouchHelper.RIGHT ? "deleted" : "archived") + ".", Snackbar.LENGTH_LONG);
                    snackbar.setAction(android.R.string.cancel, new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            mAdapter.undoDelete();
                        }
                    });
                    snackbar.show();
                    }
                    @Override
                    public void onChildDraw (Canvas c, RecyclerView
                    recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,
                    int actionState, boolean isCurrentlyActive){
                        new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
                                .addSwipeLeftBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_left_background))
                                .addSwipeLeftActionIcon(R.drawable.ic_archive_white_24dp)
                                .addSwipeRightBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_right_background))
                                .addSwipeRightActionIcon(R.drawable.ic_delete_white_24dp)
                                .addSwipeRightLabel(getString(R.string.action_delete))
                                .setSwipeRightLabelColor(Color.WHITE)
                                .addSwipeLeftLabel(getString(R.string.action_archive))
                                .setSwipeLeftLabelColor(Color.WHITE)
                                .create()
                                .decorate();
                        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                    }
                };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        CustomToast newtoast = new CustomToast(getContext(),"you clicked on this" );
        newtoast.show();

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "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 OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    private void clearFields() {
        checkInLastDateTime.setText("");
        checkInDestinationName.setText("");
        checkInTitle.setText("");
        checkInComments.setText("");
    }




    private void observerSetup() {
        Log.i(TAG, "observerSetup:");
        checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
        checkInTitle = getView().findViewById(R.id.checkInTitle);
        checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
        checkInComments = getView().findViewById(R.id.checkInComments);
        if(mViewModel.getAllCheckIn() != null)
            mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
                @Override
                public void onChanged(@Nullable final List<CheckInTable> allCheckIn) {
                    mAdapter.setCheckInList(allCheckIn);
            }
        });

    }

 }

Here is the recyclerview adapter code

package com.example.checkingin;


import android.app.Activity;
import android.content.Context;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;


public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
    private int checkInListLayout;
    private List<CheckInTable> checkInList;
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private CheckInTable mRecentlyDeletedItem;
    private int mCheckInTablePrimaryKey;
    private int mRecentlyDeletedItemPosition;
    private Context context;


    public CheckInListAdapter(int layoutId) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
    }

    public void setCheckInList(List<CheckInTable> allCheckIn) {
        checkInList = allCheckIn;
        Log.i(TAG, "setCheckInList: ");
        notifyDataSetChanged();
    }
    public void deleteItem(int position) {
        mRecentlyDeletedItem = checkInList.get(position);
        mRecentlyDeletedItemPosition = position;
        checkInList.remove(position);
        notifyItemRemoved(position);
    }

    public void undoDelete() {
        checkInList.add(mRecentlyDeletedItemPosition,
                mRecentlyDeletedItem);
        notifyItemInserted(mRecentlyDeletedItemPosition);
    }
    @Override
    public int getItemCount() {
        return checkInList == null ? 0 : checkInList.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder: ");
        View view = LayoutInflater.from(
                parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
        ViewHolder checkInListViewHolder = new ViewHolder(view);
        return checkInListViewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int listPosition) {

        TextView checkInTablePrimaryKey = holder.checkInTablePrimaryKey;
        TextView checkInLastDateTime = holder.checkInLastDateTime;
        TextView checkInTitle = holder.checkInTitle;
        TextView checkInDestinationName = holder.checkInDestinationName;
        TextView checkInComments = holder.checkInComments;
        holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
        holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);


        Log.i(TAG, "onBindViewHolder: ");

        //checkInTablePrimaryKey.setText(checkInList.get(listPosition).getCheckInTablePrimaryKey());
        checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
        checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
        checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
        checkInComments.setText(checkInList.get(listPosition).getCheckInComments());

        ImageView checkInEditButton = holder.checkInEditButton;
        ImageView checkInResendButton = holder.checkInResendButton;

        ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
        ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);

        editCheckInButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
             //put in edit check in logic

                 Integer value = (checkInList.get(listPosition).getCheckInTablePrimaryKey());
                 Intent intent = new Intent(context, CheckInNew.class);
                 intent.putExtra("checkInTablePrimaryKey",value);
                 context.startActivity(intent);

                 //Bundle extras = getIntent().getExtras();
                 //if (extras != null) {
                 //    String value = extras.getInt("checkInTablePrimaryKey");
                     //The key argument here must match that used in the other activity
                 //}
            }
          });
        resendCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in resend logic

            }
        });

    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView  checkInTablePrimaryKey;
        TextView checkInLastDateTime;
        TextView checkInTitle;
        TextView checkInDestinationName;
        TextView checkInComments;
        ImageView checkInEditButton;
        ImageView checkInResendButton;
        ViewHolder(View itemView) {
            super(itemView);
            Log.i(TAG, "ViewHolder: ");
            checkInTablePrimaryKey = itemView.findViewById(R.id.checkInTablePrimaryKey);
            checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
            checkInTitle = itemView.findViewById(R.id.checkInTitle);
            checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
            checkInComments = itemView.findViewById(R.id.checkInComments);
            checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
            checkInResendButton = itemView.findViewById(R.id.checkInResendButton);


        }
    }
}

Here is the Activity code CheckIn.java

package com.example.checkingin;

import android.net.Uri;
import android.os.Bundle;


import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;


public class CheckIn extends AppCompatActivity implements
        CheckInRecentList.OnFragmentInteractionListener,
        CheckInApproveRequested.OnFragmentInteractionListener,
        CheckInSearch.OnFragmentInteractionListener {
    //private AdView mAdView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_check_in);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        //MobileAds.initialize(this, new OnInitializationCompleteListener() {
        //    @Override
        //    public void onInitializationComplete(InitializationStatus initializationStatus) {
        //    }
        //});
        //mAdView = findViewById(R.id.adView);
        //AdRequest adRequest = new AdRequest.Builder().build();
        //mAdView.loadAd(adRequest);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerUtil.getDrawer(this,toolbar);
        configureTabLayout();

    }

    private void configureTabLayout() {
        TabLayout tabLayout = findViewById(R.id.check_in_main_tab_layout);

        tabLayout.addTab(tabLayout.newTab().setText("Recent"));
        tabLayout.addTab(tabLayout.newTab().setText("Approve Requested"));
        tabLayout.addTab(tabLayout.newTab().setText("Search"));

        final ViewPager viewPager = findViewById(R.id.check_in_main_pager);
        final PagerAdapter adapter = new CheckInMainPagerAdapter
                (getSupportFragmentManager(),
                        tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new
               TabLayout.OnTabSelectedListener() {
       @Override
       public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
       }

       @Override
       public void onTabUnselected(TabLayout.Tab tab) {

       }

       @Override
       public void onTabReselected(TabLayout.Tab tab) {

       }

       });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

    public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.check_in, menu);
        return true;
    }
}
READ  [FIXED] android - Fetched Firebase Data is not showing into Listview
Powered by Inline Related Posts
Android Tags:android-fragments, android-recyclerview, java

Post navigation

Previous Post: [FIXED] android – Convert BMP image to PNG or JPG in Java without loading the entire image in memory
Next Post: [FIXED] xml – Android – prevent TextView to push out another element inside LinearLayout

Related Posts

[FIXED] android – How can i set a conditional limit on Log_Entries which are counted? Android
[FIXED] android – How to make string-array texts as HTML formatted texts Android
[FIXED] android – Can we make nfc card readable but only to specific devices? Android
[FIXED] libGDX can not see Android SDK Android
[FIXED] android – Not able to override fonts in different views when I set a font in the app theme Android
[FIXED] android – RecyclerView with ListAdapter Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What are the main features of Islamic education?
  • Is the Jeep 4xe worth it?
  • How does the ringer work on cast iron?
  • What is the biggest size interior door?
  • Is blue raspberry an original Jolly Rancher flavor?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme