用户从微调器中选择项目,csv文件中的相应数字显示intextview

时间:2018-10-01 22:02:16

标签: android android-recyclerview

我有这样的想法,当用户按下晶圆厂时,卡片视图会添加到recyclerview布局中。用户添加的每个cardview内都有一个微调框,复选框edittext和textview。微调框由csv文件中的第一列填充。第一列具有商品名称,第二列具有与该产品相关的特定编号,其中一些可以相同

我以前有一个类似的应用程序,当用户从微调器中选择一个项目时,csv文件中的核心对应数字将显示在文本视图中。但是那没有recyclerviews或cardviews,所以我现在尝试在我的代码中实现它(使用recyclerview和cardviews)

但是,当我试图在当前的ProductAdapter(recyclerviewadapter)代码中实现该代码时,却出现了一个错误:

编译错误:

error: cannot find symbol method getResources() 

它来自这段代码

InputStream inputStream = getResources().openRawResource(R.raw.shopitems); CSVFile csvFile = new CSVFile(inputStream); final List<String> mSpinnerItems = csvFile.read();

这是我完整的ProductAdapter.java代码

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();

    private Map<String, String> numberItemValues = new HashMap<>();





    private SearchableSpinner spinner;

    //we are storing all the products in a list
    private List<Product> productList;

    private Activity create;


    //TODO CODE FOR CSV FILE


    /*InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
    CSVFile csvFile = new CSVFile(inputStream);
    final List<String>  mSpinnerItems = csvFile.read();*/


    InputStream inputStream = null;
    List<String>  mSpinnerItems = null;
    CSVFile csvFile = null;


    //TODO END OF CODE FOR CSV FILE

    public ProductAdapter(Activity activity) {
        create = activity;

    }


    //getting the context and product list with constructor
    public ProductAdapter(Activity activity, List<Product> productList) {
        // this.mCtx = mCtx;

       /* inputStream = create.getResources().openRawResource(R.raw.shopitems);
        csvFile = new CSVFile(inputStream);
        mSpinnerItems = csvFile.read();*/

        create = activity;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(create);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

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


        // //getting the product of the specified position




        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
                Product.getSpinnerItemsList());
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.spinner.setAdapter(spinnerArrayAdapter);

        holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
                mSpinnerSelectedItem.put(position, mPosition);


                TextView mTextView = view.findViewById(R.id.mSpinnerText);


                //TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
                String currentItem = mSpinnerItems.get(position);
                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);



            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //binding the data with the viewholder views
        if (mSpinnerSelectedItem.containsKey(position)) {
            holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
        }


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


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);


                // set title
                alertDialogBuilder.setTitle("Delete Item");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Are you sure you want to delete this item?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity


                                holder.checkBox.setChecked(false);
                                holder.spinner.setSelection(0);



                                productList.remove(holder.getAdapterPosition());
                                notifyItemRemoved(holder.getAdapterPosition());

                                Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();


                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });





    }


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


    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View rootView;


        public ProductViewHolder(View itemView) {
            super(itemView);

            spinner = itemView.findViewById(R.id.spinner);
            editText = itemView.findViewById(R.id.editText);
            textView5 = itemView.findViewById(R.id.textView5);
            checkBox = itemView.findViewById(R.id.checkBox);
            rootView = itemView.findViewById(R.id.linearLayout);


            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // makes the set disappear when checkbox is ticked.
                    if(isChecked){

                        checkBox.setChecked(false);
                        spinner.setSelection(0);

                        productList.remove(getAdapterPosition());
                        notifyItemRemoved(getAdapterPosition());



                        Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
                    }

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }

    //TODO CODE FOR CSV FILE
    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }


}

create.java代码,这是我的主要活动,其中添加了卡,而晶圆厂等

public class create extends AppCompatActivity {



    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;


    Product mProduct;
    private Map<String, String> numberItemValues = new HashMap<>();
    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);


        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
         CSVFile csvFile = new CSVFile(inputStream);

       final List<String>  mSpinnerItems = csvFile.read();


        //getting the recyclerview from xml
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //initializing the productlist
        productList = new ArrayList<>();
        productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));




      final ProductAdapter  adapter = new ProductAdapter(this, productList);

        //TODO FAB BUTTON
        FloatingActionButton floatingActionButton =
             findViewById(R.id.fab);


        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productList.add(mProduct);
                if(adapter != null)
                    adapter.notifyDataSetChanged();


                //Handle the empty adapter here

            }
        });









        //setting adapter to recyclerview
        recyclerView.setAdapter(adapter);






    }



    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");
                    //TODO I edited this part so that you'd add the values in our new hash map variable

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }



}

1 个答案:

答案 0 :(得分:1)

适配器了解关于// val list = List(Success(10), Success(20), Failure(new Exception("error1"))) val (failures, successes) = list.partitionMap(_.toEither) // failures: List[Throwable] = List(java.lang.Exception: error1) // successes: List[Int] = List(10, 20) 的想法。这需要来自getResources()Activity对象。这样做:

Context

然后在您的公开InputStream inputStream = null; List<String> mSpinnerItems = null; CSVFile csvFile = null; 方法中正确初始化ProductAdapter()

InputStream

当然,您可以创建一个public ProductAdapter(Activity activity, List<Product> productList) { create = activity; //INFO:: Now initialize the InputStream inputStream = create.getResources().openRawResource(R.raw.shopitems); csvFile = new CSVFile(inputStream); mSpinnerItems = csvFile.read(); this.productList = productList; } 资源,并使用该资源填充微调器视图。

string-array

然后在布局文件中:

<string-array name="my_values">
    <item>Hello</item>
    <item>World</item>
    <item>Back</item>
    <item>Again</item>
</string-array>


编辑

使用更新后的代码,您可以删除:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/my_values"
    />

来自InputStream inputStream = null; List<String> mSpinnerItems = null; CSVFile csvFile = null;

在行:

上发生的ProductAdapter错误
NullPointerException

是由于不再使用String currentItem = mSpinnerItems.get(position); 并将其设置为mSpinnerItems引起的。因此,为了获得微调器中选择的值,请执行以下操作:

null


新编辑:

holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) { mSpinnerSelectedItem.put(position, mPosition); TextView mTextView = view.findViewById(R.id.mSpinnerText); //TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW //SearchableSpinner spinner = (SearchableSpinner)view; String currentItem = holder.spinner.getItemAtPosition(mPosition).toString(); // or try // spinner.getAdapter.getItem(mPosition).toString(); String aisleNumber = numberItemValues.get(currentItem); holder.textView5.setText(aisleNumber); } @Override public void onNothingSelected(AdapterView<?> parent) { } });

使用此:

ProductAdapter

并在“创建” public ProductAdapter(Activity activity, List<Product> productList, HashMap<String, String> numberList) { numberItemValues = numberList; create = activity; this.productList = productList; } 中更改此行:

Activity