在回收站视图中获取序列号

时间:2018-09-25 12:15:40

标签: android android-recyclerview

AmountCartModel.java

public class AmountCartModel {


private String testName;
private String testPrice;
private String serialNumber;
private Integer totalPrice;


public AmountCartModel() {
    this.testName = testName;
    this.testPrice = testPrice;
    this.serialNumber = serialNumber;
    this.totalPrice = totalPrice;
}


public String getTestName() {
    return testName;
}

public void setTestName(String testName) {
    this.testName = testName;
}

public String getTestPrice() {
    return testPrice;
}

public void setTestPrice(String testPrice) {
    this.testPrice = testPrice;
}

public String getSerialNumber() {
    return serialNumber;
}

public void setSerialNumber(String serialNumber) {
    this.serialNumber = serialNumber;
}

public Integer getTotalPrice() {
    return totalPrice;
}

public void setTotalPrice(Integer totalPrice) {
    this.totalPrice = totalPrice;
}

}

AmountCartActivity.java

    public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.total_price)
    TextView totalPriceDisplay;

    SharePreferenceManager<LoginModel> sharePreferenceManager;

    private RecyclerView recyclerView;

    List<AmountCartModel> mydataList ;

    private MyAdapter madapter;

    Bundle extras ;
    String testName="";
    String testPrice="";
    String totalPrice= "";

    int counting = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amount_cart);
        ButterKnife.bind(this);


        sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());


     showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));


        mydataList = new ArrayList<>();
        /*
        * Getting Values From BUNDLE
        * */
        extras = getIntent().getExtras();

        if (extras != null) {

            testName = extras.getString("test_name");
            testPrice = extras.getString("test_price");
            totalPrice = String.valueOf(extras.getInt("total_price"));

            counting = extras.getInt("serialNumber");

            //Just add your data in list
            AmountCartModel mydata = new AmountCartModel();  // object of Model Class
            mydata.setTestName(testName );
            mydata.setTestPrice(testPrice);

            mydata.setTotalPrice(Integer.valueOf(totalPrice));

            mydata.setSerialNumber(counting);

            mydataList.add(mydata);


        }


        madapter=new MyAdapter(mydataList);
        madapter.setMyDataList(mydataList);
        recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(madapter);
}
}

AmountCartAdapter.java

     public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> 
    {

        private List<AmountCartModel> context;
        private List<AmountCartModel> myDataList;

        public MyAdapter(List<AmountCartModel> context) {
            this.context = context;
            myDataList = new ArrayList<>();
        }



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

            // Replace with your layout
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
            return new ViewHolder(view);
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // Set Your Data here to yout Layout Components..

            // to get Amount
           /* myDataList.get(position).getTestName();
            myDataList.get(position).getTestPrice();*/


            holder.testName.setText(myDataList.get(position).getTestName());

       holder.testPrice.setText(myDataList.get(position).getTestPrice());

       holder.textView2.setText(myDataList.get(position).getSerialNumber());


        }


        @Override
        public int getItemCount() {
            /*if (myDataList.size() != 0) {
                // return Size of List if not empty!
                return myDataList.size();
            }
            return 0;*/
            return myDataList.size();
        }


        public void setMyDataList(List<AmountCartModel> myDataList) {
            // getting list from Fragment.
            this.myDataList = myDataList;
            notifyDataSetChanged();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {

            TextView testName,testPrice,textView2;


            public ViewHolder(View itemView) {
                super(itemView);
                // itemView.findViewById

                testName=itemView.findViewById(R.id.test_name_one);
                testPrice=itemView.findViewById(R.id.test_price);
                textView2=itemView.findViewById(R.id.textView2);
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();

        startActivity(new 
     Intent(AmountCartActivity.this,HealthServicesActivity.class));
        finish();
    }
    }

HealthCartActivity

 public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {


    private ImageView imlogo;
    private TextView Date;
    private TextView Time;
    private TextView Day;

    private ImageView settingsButton;

    @BindView(R.id.back_to_add_patient)
    TextView backToDashboard;

    int totalAmount = 0;
    int totalPrice = 0;
    String testName = "";
    String testPrice = "";
    int count = 0;

    /*
    *Api call
    * */
    private RecyclerView recyclerView;
    private ArrayList<TestListModel> mydataList;
    private RecyclerAdapter madapter;


    private ArrayList<TestListModel> mydb;

    private Button submitButton;

    private TextView deviceModeName;
    private TextView centerId;

    SharePreferenceManager<LoginModel> sharePreferenceManager;

    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_services);
        ButterKnife.bind(this);

        sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());


        imlogo=(ImageView) findViewById(R.id.action_bar_logo);
        Day=(TextView) findViewById(R.id.day);
        Date=(TextView) findViewById(R.id.date);
        Time=(TextView)findViewById(R.id.time);
        //backButton=(Button) findViewById(R.id.back_button);
        centerId=(TextView)findViewById(R.id.center_id);
        deviceModeName=(TextView)findViewById(R.id.device_mode_name);

        settingsButton=(ImageView)findViewById(R.id.settings);

        submitButton=(Button) findViewById(R.id.submit_button);

        dayTimeDisplay();

        showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));


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


                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(HealthServicesActivity.this, settingsButton);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                        .inflate(R.menu.common_navigation_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {

                        int id = item.getItemId();

                        if (id==R.id.home){

                            startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
                            finish();
                        }

                        if (id==R.id.my_profile){

                            startActivity(new Intent(getApplicationContext(), MyProfileActivity.class));
                            finish();
                        }

                        if (id==R.id.change_password){

                            startActivity(new Intent(getApplicationContext(), ChangePasswordActivity.class));
                            finish();
                        }

                        Toast.makeText(HealthServicesActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu

            }
        });


        progressDialog = new ProgressDialog(HealthServicesActivity.this);
        progressDialog.setMessage("Please Wait...");
        progressDialog.setCanceledOnTouchOutside(false);

        //registerOnline();

        initViews();

        submitButton.setOnClickListener(this);
        backToDashboard.setOnClickListener(this);
    }


    /*
    * Action Bar DATE N TIME
    * */
    private void dayTimeDisplay(){

        SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE");
        java.util.Date d = new Date();
        String dayOfTheWeek = sdf1.format(d);
        Day.setText(dayOfTheWeek);

        String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
        Date.setText(currentDateTimeString);

        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
        String time1 = sdf.format(dt);
        Time.setText(time1);

    }


    /*
    * On Click Listner
    * */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

                    case R.id.submit_button:

                        AtomicInteger sharedOutput = new AtomicInteger(0);

                        List<TestListModel> stList = ((RecyclerAdapter) madapter)
                                .getTestList();


                       for (int i = 0; i < stList.size(); i++) {
                            TestListModel singleStudent = stList.get(i);

                           if (singleStudent.isSelected() == true) {

                               //testListId = testListId+ "\n" + singleStudent.getTestlist_id().toString();

                               testName = testName + "\n" + singleStudent.getTest_name().toString();
                               testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();

                                //count = singleStudent.setSerial_number("\n" +i);

                                //singleStudent.getSerial_number(count);

                               count ++;


                               /* count = sharedOutput.get() + 1;
                                System.out.println(count);
                                sharedOutput.incrementAndGet();*/

                                totalAmount = Integer.parseInt(stList.get(i).getTest_price());

                                totalPrice = totalPrice + totalAmount;


                            }
                       }




                        Toast.makeText(HealthServicesActivity.this,
                                "Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
                                .show();


                        Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);


                        in.putExtra("test_name", testName);
                        in.putExtra("test_price", testPrice);
                        in.putExtra("total_price", totalPrice);
                        in.putExtra("serial_number", count);



                        startActivity(in);

                        finish();

                        break;



                    /** back Button Click
                    * */
                    case R.id.back_to_add_patient:
                    startActivity(new Intent(getApplicationContext(), PatientActivity.class));
                    finish();
                    break;


            default:
                break;

        }
    }



    /** show center Id in action bar
     * */
    @Override
    protected void onResume() {
        super.onResume();
        showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));


    }


    private void showcenterid(LoginModel userLoginData) {
        centerId.setText(userLoginData.getResult().getGenCenterId());
        centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
        deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
    }


    private void initViews() {
        recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }


    private void loadJSON() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(" http://192.168.1.80/aoplnew/api/")
//                .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiInterface request = retrofit.create(ApiInterface.class);
        Call<JSONResponse> call = request.getTestLists();
        call.enqueue(new Callback<JSONResponse>() {


            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {


                JSONResponse jsonResponse = response.body();
                mydataList = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
                madapter = new RecyclerAdapter(mydataList);
                recyclerView.setAdapter(madapter);


            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }


}

无论我使用复选框从以前的HealthCartActivity中选择的哪个,我都尝试在我的Recycler视图的AmountCartActivity中显示序列号。而且,我已经实现了一些代码,但是我没有获得序列号。

7 个答案:

答案 0 :(得分:0)

您必须在serialNumber上添加AmountCartModel。这样可以解决您的问题

答案 1 :(得分:0)

如下所示在您的AmountCartModel中放置一个ID;

limit

然后从每个视图检索此序列号。 由于您要发送意图表单onBackPressed();将该列表作为附加内容附加到意图上,

[
  {
    $group: {
      _id: "$myDoc,homepage_domain",
      count: {$sum: 1},
      entry: {
        $push: {
          location_city: "$myDoc.location_city",
          homepage_domain: "$myDoc.homepage_domain",
          country: "$myDoc.country",
          employee_linkedin: "$myDoc.employee_linkedin",
          linkedin_url: "$myDoc.inkedin_url",
          homepage_url: "$myDoc.homepage_url",
          industry: "$myDoc.industry",
          read_at: "$myDoc.read_at"
        }
      }
    }
  }, {
    $limit : 50000
  }, {
    $skip: 50000
  }
],
{
  allowDiskUse: true
},
print(
  db.Or9.insert({
    "HomepageDomain":myDoc.homepage_domain,
    "location_city":myDoc.location_city
  })
)

请确保您要从中扩展列表的对象(AmountCarModel)扩展了Parcelable,并在onResume()的HealthServiceActivity中捕获它

或者,也许是最好的方法,是在如下所示的Retrofit onResponse()方法中将序列号附加到HealthServiceActivity内;

public class AmountCartModel {

private int serialNumber; // add this line
private String testName;
private String testPrice;
private Integer totalPrice;


public AmountCartModel() {
    this.serialNumber= serialNumber; // add this line
    this.testName = testName;
    this.testPrice = testPrice;
    this.totalPrice = totalPrice;
}

public int getSerialNumber (){
} // add this line

public void setSerialNumber(int serialNumber) {
}// add this line also

答案 2 :(得分:0)

好吧,您可以解决。而且您不必仅在模型中保留serialNumber变量即可跟踪其位置。

您可以将position的{​​{1}}参数变量用于序列号和计数。

onBindViewHolder()

答案 3 :(得分:0)

在AmountCartModel中,serialNumber的数据类型为String

在放置对象的同时进行设置    计数= extras.getInt(“ serialNumber”);

        //Just add your data in list
        AmountCartModel mydata = new AmountCartModel();  // object of Model Class
        mydata.setTestName(testName );
        mydata.setTestPrice(testPrice);

        mydata.setTotalPrice(Integer.valueOf(totalPrice));

        mydata.setSerialNumber(counting);

并且您将其存储在ArrayList中,而没有for循环,因此每次只有一个对象包含在您的arraylist中

答案 4 :(得分:0)

尝试这种方式

int count = 0;
@Override
    public void onClick(View v) {

        switch (v.getId()) {

                    case R.id.submit_button:

                        int totalAmount = 0;
                        int totalPrice = 0;
                        String testName = "";
                        String testPrice="";




                        List<TestListModel> stList = ((RecyclerAdapter) madapter)
                                .getTestList();


                       for (int i = 0; i < stList.size(); i++) {
                            TestListModel singleStudent = stList.get(i);

                           //AmountCartModel serialNumber = stList.get(i);


                           if (singleStudent.isSelected() == true) {

                                testName = testName + "\n" + singleStudent.getTest_name().toString();
                                testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();


                                count++;

                                totalAmount = Integer.parseInt(stList.get(i).getTest_price());

                                totalPrice = totalPrice + totalAmount;

                            }
                       }


                        Toast.makeText(HealthServicesActivity.this,
                                "Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
                                .show();


                        Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);

                        in.putExtra("test_name", testName);
                        in.putExtra("test_price", testPrice);
                        in.putExtra("total_price", totalPrice);
                        in.putExtra("serialNumber", count);
                        startActivity(in);

                        finish();

                        break;



                    /** back Button Click
                    * */
                    case R.id.back_to_add_patient:
                    startActivity(new Intent(getApplicationContext(), PatientActivity.class));
                    finish();
                    break;


            default:
                break;

        }
    }

答案 5 :(得分:0)

我找到了答案。我已经完成了如下序列号的代码。在这里,我在元素前面得到序列号。在此代码中,我获取了一个int变量并使用值1进行了初始化。此后,我在for循环中调用srNo变量,然后在for循环的末尾递增。

                    int srNo = 1;

                    List<TestListModel> stList = ((RecyclerAdapter) madapter)
                            .getTestList();


                   for (int i = 0; i < stList.size(); i++) {
                        TestListModel singleStudent = stList.get(i);

                       if (singleStudent.isSelected() == true) {


                           testListId = testListId+ "\n" + Integer.parseInt(String.valueOf(srNo));

                           testName = testName + "\n" + singleStudent.getTest_name().toString();
                           testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();

                           srNo++;

                            totalAmount = Integer.parseInt(stList.get(i).getTest_price());

                            totalPrice = totalPrice + totalAmount;


                        }
                   }

答案 6 :(得分:0)

@Override
    public void onBindViewHolder(ViewHolder holder, int position) 
    holder.id.setText(String.valueOf(" "+(position+1)));

使用上述方法。