我们如何在RecylerView适配器中使用按钮单击时使用fragement

时间:2017-03-23 15:31:33

标签: android android-fragments

这是一个完整的适配器代码
 它显示错误NULL对象请解决请告诉如何错误删除...........                 包com.softedge.visioneering.tfd.adapters;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.softedge.visioneering.tfd.R;
import com.softedge.visioneering.tfd.fragments.Status_update_Fragment;
import com.softedge.visioneering.tfd.models.OrdersListModel;
import com.softedge.visioneering.tfd.utils.Status_update;

import java.util.List;

import static android.app.PendingIntent.getActivity;

/**
 * Created by Atish Agrawal on 04-12-2016.
 */

public class MyOrdersAdapter extends RecyclerView.Adapter<MyOrdersAdapter.MyOrdersViewHolder> {

    private List<OrdersListModel> list;
    private Context context;
    private LayoutInflater layoutInflater;


    public MyOrdersAdapter(Context passedContext, List<OrdersListModel> passedModels) {

        this.context = passedContext;
        this.list = passedModels;

    }

    @Override
    public MyOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View convertview = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.inner_list_orders, parent, false);


        return new MyOrdersViewHolder(convertview);


    }

    @Override
    public void onBindViewHolder(MyOrdersViewHolder holder, int position) {

        holder.txtOrderDescription.setText("Title: " + list.get(position).getOrderTitle());
        holder.txtOrderQuantity.setText("Order No.: " + list.get(position).getOrderNumber());
        holder.txtOrderStatus.setText("Status: " + list.get(position).getOrderStatus());
        holder.txtOrderDate.setText("Order Date: " + list.get(position).getOrderCreationDate());
        holder.txtExpectedDate.setText("Exp. Date: " + list.get(position).getExpectedOrderCompletionDate());
        holder.txtCreatedBy.setText("Assign to: " + list.get(position).getAssignToFirstName() + " " + list.get(position).getAssignToLastName());
        holder.txtOrderStatus_Per.setText(list.get(position).getOrderStatusPercentage()+"%");



        if(holder instanceof MyOrdersViewHolder) {

            holder.update_btwn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    FragmentManager fragmentManager =getSupportFragmentManager();
                    //FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentManager.beginTransaction().add(R.id.cardViewStudentList, new Status_update_Fragment().newInstance()).addToBackStack("AddEvent").commit();
                    //fragmentTransaction.commit();

                }

                private FragmentManager getSupportFragmentManager() {
                    return null;
                }


            });
        }



    }

    @Override
    public int getItemCount() {
        return list.size();
    }




    public class MyOrdersViewHolder extends RecyclerView.ViewHolder {

        public TextView txtOrderDescription, txtOrderQuantity, txtOrderStatus, txtOrderDate, txtExpectedDate, txtCreatedBy,txtOrderStatus_Per;

        public Button update_btwn;
        public MyOrdersViewHolder(View convertView) {
            super(convertView);

            update_btwn=(Button) convertView.findViewById(R.id.status_update_button);
            txtOrderDescription = (TextView) convertView.findViewById(R.id.txtOrderDescription);
            txtOrderQuantity = (TextView) convertView.findViewById(R.id.txtOrderQuantity);
            txtOrderStatus = (TextView) convertView.findViewById(R.id.txtOrderStatus);
            txtOrderStatus_Per=(TextView)convertView.findViewById(R.id.txtOrder_Status_per);
            txtOrderDate = (TextView) convertView.findViewById(R.id.txtOrderDate);
            txtExpectedDate = (TextView) convertView.findViewById(R.id.txtExpectedDate);
            txtCreatedBy = (TextView) convertView.findViewById(R.id.txtCreatedBy);

            /*update_btwn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentManager.beginTransaction().add(R.id.cardViewStudentList, new Status_update_Fragment().newInstance()).addToBackStack("AddEvent").commit();
                    fragmentTransaction.commit();

                }

                private FragmentManager getSupportFragmentManager() {
                    return null;
                }


            });*/




    }


    }
}

代码是适配器代码:         鞋子错误,我尝试了很多次,但它没有解决。         我正在使用RecylerView显示文本。     在那里我放置了一个按钮,想要在Button Click上调用片段     请告诉我解决方案

这是我的JAVA API类从我称之为适配器类:

public class OrdersListAPI扩展了AsyncTask {

private static final String TAG = OrdersListAPI.class.getSimpleName();
private ProgressDialog progressDialog = null;
private String jsonString, response = "";

private OrdersListModel ordersListModel;
private RecyclerView recyclerViewOrders;
private List<OrdersListModel> ordersListModels;
private MyOrdersAdapter myOrdersAdapter;


private Context context;

/**
 * @param callingContext Context of the calling activity
 */

public OrdersListAPI(Context callingContext, RecyclerView passedRecyclerViewOrders,
                     List<OrdersListModel> passedOrderListModels,
                     MyOrdersAdapter passedAdapter, String passedJSON) {
    // Initializing the variables

    this.context = callingContext;
    this.recyclerViewOrders = passedRecyclerViewOrders;
    this.myOrdersAdapter = passedAdapter;
    this.ordersListModels = passedOrderListModels;
    this.jsonString = passedJSON;


}

@Override
protected void onPreExecute() {
    // Displaying a progressBar
    super.onPreExecute();

    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Please wait...");
    progressDialog.setCancelable(false);
    progressDialog.show();

}

/*
 * (non-Javadoc)
 *
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected Boolean doInBackground(Void... arg0) {
    // Checking Internet connection

    if (ProjectUtils.isConnectedToInternet(context)) {

        // Connected to internet

        try {

            /**
             * Preparing the URL of the Webserver API
             */

            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(ApplicationUtils.RECIEVED_ORDERS_LIST_API);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");


            /**
             *
             * Adding the JSON object to the HTTP-POST
             */

            StringEntity entity = new StringEntity(jsonString.toString());
            httpPost.setEntity(entity);

            /**
             * Making call to the server
             */

            HttpResponse httpResponse = client.execute(httpPost);

            /**
             * Checking the response from the server
             */

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {

                HttpEntity httpEntity = httpResponse.getEntity();

                /**
                 * Fetching response from the server
                 */

                response = EntityUtils.toString(httpEntity);

                if (ApplicationUtils.isLogEnabled)
                    Log.d(TAG, "Response: " + response.trim());


                // Processing the response

                JSONArray ordersArray = new JSONArray(response);

                for (int i = 0; i < ordersArray.length(); i++) {

                    JSONObject orderJSONObject = ordersArray
                            .getJSONObject(i);

                    /**
                     * Initialising Orders Model
                     */

                    ordersListModel = new OrdersListModel();

                    JSONObject order_det_JSONObject=orderJSONObject.getJSONObject(JSONUtils.EO_ORDER_DETAILS);
                    JSONObject assignToJSONObject = orderJSONObject.getJSONObject(JSONUtils.ASSIGNED_TO);

                    if (TextUtils.equals(assignToJSONObject.getString("primaryKey"),"11")) {
                        /**
                         * Fetching Order Details
                         */

                        ordersListModel.setOrderTitle(order_det_JSONObject.getString(JSONUtils.ORDER_TITLE));
                        ordersListModel.setOrderNumber(order_det_JSONObject.getString(JSONUtils.ORDER_NUMBER));
                        ordersListModel.setOrderStatus(order_det_JSONObject.getString(JSONUtils.ORDER_STATUS));
                        ordersListModel.setOrderCreationDate(order_det_JSONObject.getString(JSONUtils.ORDER_CREATION_DATE));
                        ordersListModel.setExpectedOrderCompletionDate(order_det_JSONObject.getString(JSONUtils.EXPECTED_ORDER_COMPLETION_DATE));
                        ordersListModel.setOrderStatusPercentage(order_det_JSONObject.getString(JSONUtils.ORDER_STATUS_PERCENTAGE));

                        /**
                         * Fetching User Details
                         */
                        //This Show Assign not Created_By
                        //JSONObject createdByJSONObject = orderJSONObject.getJSONObject(JSONUtils.ASSIGNED_TO);

                        ordersListModel.setAssignToFirstName(assignToJSONObject.getString(JSONUtils.FIRST_NAME));
                        ordersListModel.setAssignToLastName(assignToJSONObject.getString(JSONUtils.LAST_NAME));

                        ordersListModels.add(ordersListModel);
                    }
                }

                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return null;
}

@Override
protected void onPostExecute(Boolean result) {
    // Moving to new activity and removing the progress dialog
    super.onPostExecute(result);
    if (progressDialog != null && progressDialog.isShowing())
        progressDialog.dismiss();


    // context.startActivity(new Intent(context, Dashboard.class));
    //((Activity) context).finish();

    if (result == null) {

        // User not connected to internet

        Toast.makeText(context, "No Internet connection",
                Toast.LENGTH_SHORT).show();

        return;

    }
    if (result) {

        // Server returned true

        /**
         * Process Response
         */
        myOrdersAdapter = new MyOrdersAdapter(context, ordersListModels);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
        recyclerViewOrders.setLayoutManager(mLayoutManager);
        recyclerViewOrders.setItemAnimator(new DefaultItemAnimator());
        recyclerViewOrders.setAdapter(myOrdersAdapter);

        myOrdersAdapter.notifyDataSetChanged();


    }


}

}

这是一个JAVA API,它来自Load Recyler Adapter

2 个答案:

答案 0 :(得分:1)

listener代码移至onBindViewHolder()

  @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof MyOrdersViewHolder) {
           holder.update_btwn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        fragmentManager.beginTransaction().add(R.id.cardViewStudentList, new Status_update_Fragment().newInstance()).addToBackStack("AddEvent").commit();
                        fragmentTransaction.commit();

                    }

                    private FragmentManager getSupportFragmentManager() {
                        return null;
                    }


                });
        }
    }

编辑,对于您的其他错误,我猜这个上下文是android.app.Activity,然后在导入android.app.Activity后在适配器中执行此操作:

((Activity)context).getSupportFragmentManager();

OR 只需使用您调用适配器的活动的类名:

 ((YOUR_ACTIVITY_NAME)context).getSupportFragmentManager();

而不是:getSupportFragmentManager();

答案 1 :(得分:0)

Solutions is :

    final FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();