The adapter doesn't work in some functions

66
January 09, 2019, at 05:20 AM

I did a recycleview job to display some data and I actually succeeded when I created it inside some functions such as the onCreateView method and the load method, and then dialog the function of displaying a window with buttons, and when I called the adapter and appended a null method inside to test it, I didn't succeed.

The name of the method that caused that problem is adapter.refreshevents();. I don't know. I tried too much. Please put the code necessary to correct the error.

public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public final int TYPE_MOVIE = 0;
    public final int TYPE_LOAD = 1;
    static Context context;
    List<Customer>customers;
    OnLoadMoreListener loadMoreListener;
    boolean isLoading = false, isMoreDataAvailable = true;
    public CustomerAdapter(Context context, List<Customer> customers) {
        this.context = context;
        this.customers = customers;
    }

    public void refreshEvents() {
        //List<Customer> events
        //events.clear();
        //events.addAll(events);
        //this.notifyDataSetChanged();
        Log.i("adpter_22","yesysy");
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        if(viewType==TYPE_MOVIE){
            return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
        }else{
            return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
            isLoading = true;
            loadMoreListener.onLoadMore();
        }

        if(getItemViewType(position)==TYPE_MOVIE){
            ((CustomerHolder)holder).bindData(customers.get(position));
            if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
              //  function call a volly function .. //..
              // if(customers.get(position).user_id==2)((CustomerHolder)holder).imgLock.setVisibility(View.VISIBLE);
              ((CustomerHolder)holder).buttonViewOption.getRootView().toString();
           //    Toast.makeText(context,"Index Is "+customers.get(position).status+"usr_id"+customers.get(position).user_id, Toast.LENGTH_SHORT).show();
                //Page_6Fragment.newInstance().sendNotfic(context ,customers.get(position).user_id);
                   // Call a fucntion to
              Page_6Fragment.newInstance().showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
                }
            });
        }
    }

    @Override
    public int getItemViewType(int position) {
        if(customers.get(position).type.equals("movie")){
            return TYPE_MOVIE;
        }else{
            return TYPE_LOAD;
        }
    }

    @Override
    public int getItemCount(){
       return customers.size();
    }
    /* VIEW HOLDERS */
    static class CustomerHolder extends RecyclerView.ViewHolder{
        TextView tvTitle;
        TextView tvRating;
        ImageView imgLock;
        //  int usrid;
        Button buttonViewOption;
        public CustomerHolder(View itemView){
            super(itemView);
            tvTitle=(TextView)itemView.findViewById(R.id.title);
            tvRating=(TextView)itemView.findViewById(R.id.rating);
            imgLock=(ImageView)itemView.findViewById(R.id.img_lock);
            buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
        }

        void bindData(Customer cust){
           tvTitle.setText(cust.name);
           tvRating.setText(cust.title);
           // if(cust.user_id==2)imgLock.setVisibility(View.GONE);
            if(cust.status!=0)buttonViewOption.setBackground(context.getResources().getDrawable(R.drawable.lock));
            //  imgLock.setVisibility(View.VISIBLE);
        }
    }

    static class LoadHolder extends RecyclerView.ViewHolder{
        public LoadHolder(View itemView){
            super(itemView);
        }
    }
    public void setMoreDataAvailable(boolean moreDataAvailable) {
        isMoreDataAvailable = moreDataAvailable;
    }
    /* notifyDataSetChanged is final method so we can't override it
         call adapter.notifyDataChanged(); after update the list
    */
    public void notifyDataChanged(){
        notifyDataSetChanged();
        isLoading = false;
    }
    public interface OnLoadMoreListener{
        void onLoadMore();
    }

    public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }
}
// Fragment class 
public class Page_6Fragment extends android.support.v4.app.Fragment implements 
  AdapterView.OnItemSelectedListener {
    TextView t1,t2,t3,t4;
    Spinner spin,spin2,spin3,spin4;
    Dialog dialog;
    RecyclerView recyclerView;
    List<Customer>customers;
    CustomerAdapter adapter;
    View rootView;
    String TAG = "MainActivity - ";
    Context context;
    API api;
    Activity a;
    Boolean acceptOrNo = true;

    public static Page_6Fragment newInstance(){
        Page_6Fragment fragment = new Page_6Fragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_customer, container, false);
        //View rootView = inflater.inflate(R.xml.pref, container, false);
        //Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
        // startActivity(intent);
        this.context = getActivity();
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        customers = new ArrayList<>();
        adapter = new CustomerAdapter(context,customers);
        adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
            @Override
            public void onLoadMore() {
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        int index = customers.size();
                     //   loadMore(index);
                    }
                });
                //Calling loadMore function in Runnable to fix the
                // java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
            }
        });
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        api = ServiceGenerator.createService(API.class);
        load(0);
      return rootView;
    }

     //  recyclerView.addItemDecoration(new VerticalLineDecorator(2));
    private void load(int index){
        Call<List<Customer>> call = api.getCustomer(index);
        call.enqueue(new Callback<List<Customer>>(){
            @Override
            public void onResponse(Call<List<Customer>> call, final Response<List<Customer>> response){
                // Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
               //Log.i("TRUE_TRUE_","Yes "+response.body().get(2).name);
                if(response.isSuccessful()){
                 //Log.i("TRUE_TRUE3","Yes"+response.body().toString());
                 //movies.addAll(response.body());
                 //adapter.notifyDataChanged();
                 getActivity().runOnUiThread(new Runnable(){
                 public void run(){
                  // No.1 ..............
                  // ShowDataScreen();
                   // Toast.makeText( MainActivity.this, "ShowDataScreen",Toast.LENGTH_SHORT).show();
                       customers.addAll(response.body());
                        adapter.notifyDataChanged();
                         }});// end of No.1 UI new thread
                        getActivity().runOnUiThread(new Runnable(){
                        public void run() {//No.2
                           // Toast.makeText( MainActivity.this, "This is correct way",Toast.LENGTH_SHORT).show();
                        }});// end of No.2 UI new thread
                      // Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
                }else{
                    Log.e(TAG," Response Error "+String.valueOf(response.code()));
                }
            }
            @Override
            public void onFailure(Call<List<Customer>> call, Throwable t) {
                Log.e(TAG," Response Error "+t.getMessage());
            }
        });
    }

    private void loadMore(int index){
         // add loading progress view ....
         Log.i("first_","length "+customers.size());// = 2
         customers.add(new Customer("load"));
         Log.i("fxcv_","length "+customers.size());// = 2
         adapter.notifyItemInserted(customers.size()-1);
         Log.i("lastV_","length "+customers.size());// = 2
         //Log.i("customers.size() ","Yes "+customers.size()); // = 4 -1 =3
         Log.i("Index_","Yes "+index);// = 2
         Call<List<Customer>>call = api.getCustomer(index);
         call.enqueue(new Callback<List<Customer>>(){
            @Override
            public void onResponse(Call<List<Customer>> call, Response<List<Customer>>response) {
                if(response.isSuccessful()){
                    // remove loading view .......
                    Log.i("befor_","length "+customers.size());// = 2
                   customers.remove(customers.size()-1);
                    Log.i("after_","length "+customers.size());// = 2
                   // Log.i("LastItemRemove","Yes "+response.body().get(2).name);// = 2
                    List<Customer>result=response.body();
                    if(result.size()>0){
                        // add loaded data
                      customers.addAll(result);
                    }else{//result size 0 means there is no more data available at server
                     adapter.setMoreDataAvailable(false);
                        //telling adapter to stop calling load more as no more server data available
                        Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
                    }
                  adapter.notifyDataChanged();
                    //should call the custom method adapter.notifyDataChanged here to get the correct loading status
                }else{
                    Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
                }
            }
            @Override
            public void onFailure(Call<List<Customer>>call,Throwable t) {
                Log.e(TAG," Load More Response Error "+t.getMessage());
            }
        });
    }

    private void sendNotfic(Context mConttext, final int id, final int currentIndex, final String accept_refuse , final String day , final String hour) {
        RequestQueue queue = Volley.newRequestQueue(mConttext );
        // String url = "http://192.168.1.3/Pagination/sendNotifaction.php";
        String url =  "https://ahmedco.000webhostapp.com/sendNotifaction.php";
        // Instantiate the RequestQueue.
        // RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        //this is the url where you want to send the request
        //TODO: replace with your own url to send request, as I am using my own localhost for this tutorial
        // Request a string response from the provided URL.
         StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                      // Display the response string.
                      Log.i("Response","yes_"+response.toString());
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Response","no" + error);
            }
        }) {
            //adding parameters to the request
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("getToken", String.valueOf(currentIndex));
                params.put("title",accept_refuse);
                params.put("masg",day);
                params.put("hour",hour);
                params.put("id", String.valueOf(id));
                return params;
            }
        };
        // Add the request to the RequestQueue.
        queue.add(stringRequest);
    }

    public void showDialog(final Context context , final int getToken , final int id){
      /// here error
        adapter.refreshEvents();
        dialog = new Dialog(context);
        dialog.setCancelable(true);
        // dialog.setTitle("استقبال الطلب");
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.layout);
        dialog.show();
        String[] bankNames = {
                "O","B","H","N","j"
        };
        t1= (TextView)dialog.findViewById(R.id.tv_h);
        t2= (TextView)dialog.findViewById(R.id.tv_m);
        t3= (TextView)dialog.findViewById(R.id.tv_title);
        t4= (TextView)dialog.findViewById(R.id.tv_pam);
        spin =(Spinner)dialog.findViewById(R.id.spinner_minutes);
        spin2 =(Spinner)dialog.findViewById(R.id.spinner_minutes2);
        spin3 =(Spinner)dialog.findViewById(R.id.spinner_minutes3);
        spin4 =(Spinner)dialog.findViewById(R.id.tex);
        spin.setOnItemSelectedListener(this);
        spin2.setOnItemSelectedListener(this);
        spin3.setOnItemSelectedListener(this);
        spin4.setOnItemSelectedListener(this);
        RadioButton radioButton2 = (RadioButton)dialog.findViewById(R.id.second2);
        RadioButton radioButton = (RadioButton)dialog.findViewById(R.id.second);
        RadioGroup radioGroup = (RadioGroup)dialog.findViewById(R.id.radioSex);
        ArrayAdapter<String> a = new ArrayAdapter<String>(context,R.layout.spinner_item,bankNames);
        //ArrayAdapter b = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames2);
        //a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //spin.setAdapter(a);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton)dialog.findViewById(checkedId);
                if (checkedId == R.id.second2) {
                   RadioYes();
                   acceptOrNo = false;
                } else if (checkedId == R.id.second) {
                   acceptOrNo = true;
                   RadioNo();
             }
            }
        });

        Button btnOk = (Button)dialog.findViewById(R.id.button_cancel);
        btnOk.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
        //TODO Auto-generated method stub
        // Log.i("trace_u",""+acceptOrNo);
        if(acceptOrNo)sendNotfic(context , id , getToken ,"1" , spin4.getSelectedItem().toString() ,  "الساعه"+spin.getSelectedItem().toString()+":"+spin2.getSelectedItem().toString()+" "+spin3.getSelectedItem().toString());
        else
        sendNotfic(context , id , getToken ,"2","--" ,"--");
                dialog.dismiss();
            }
        });
        Button btnNo = (Button)dialog.findViewById(R.id.button_set);
        btnNo.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
        // TODO Auto-generated method stub
                dialog.dismiss();
          }
        });
    }
  • High-quality movie novelties from m4ufree right here and now . Top free tv shows and movies xmovies8 now
READ ALSO
Unable to load saved value in MultiselectList chosen

Unable to load saved value in MultiselectList chosen

Hi Im new on using ListBox MultiSelectList , My problem is I cant fetch the value onload of my page, Here is my Code

49
End x-axis on last data point (scatter plot) for x,y numeric values

End x-axis on last data point (scatter plot) for x,y numeric values

When I plot a dataset of (x,y) floats on a scatter plot using ChartJS, I end up with extra space on my x-axis due to the step sizeCan I force it to end right on the last data point?

46
What do we actually import from Express in a Node.js program

What do we actually import from Express in a Node.js program

Usually when we import something in Node, we do something like:

64
Python: How do I pass variables between class instances or get the caller?

Python: How do I pass variables between class instances or get the caller?

In foo, I am doing something that produces "var1" being set to 1 In bar, I would like to access the contents of var1

51