如何访问我的csv文件的一部分-android

时间:2018-08-10 05:19:39

标签: android csv

我遵循了有关如何将CSV文件链接到android studio的教程,因此我可以在下拉菜单中查看来自CSV的一行元素。 (左行用于'number',右行用于'items'。

但是现在我想弄清楚:

当用户从下拉列表中选择一项时,相应的“数字”(来自csv)显示在TextView上。

这可能吗?关于如何使它正常工作的任何想法?

谢谢!

MyListAdapter.java

public class MyListAdapter extends ArrayAdapter<String> {
    int groupid;
    List<String> items;
    Context context;
    String path;

    public MyListAdapter(Context context, int vg, int id, List<String> items) {
        super(context, vg, id, (List<String>) items);
        this.context = context;
        groupid = vg;
        this.items = items;

    }

    static class ViewHolder {
        public TextView textid;
        public TextView textname;

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        {

            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(groupid, parent, false);
                ViewHolder viewHolder = new ViewHolder();
                viewHolder.textid = (TextView) rowView.findViewById(R.id.txtid);
                viewHolder.textname = (TextView) rowView.findViewById(R.id.txtname);
                rowView.setTag(viewHolder);
            }
            // Fill data in the drop down.
            ViewHolder holder = (ViewHolder) rowView.getTag();
            String row = items.get(position);
            //holder.textid.setText(row[0]); //prints aisle number, dont need

            holder.textname.setText(row);


            return rowView;
        }

    }


}

create.java

public class create extends AppCompatActivity {


    private LinearLayout mLinearLayout;
    private ArrayList<SearchableSpinner> mSpinners;
    //TODO add the below list of buttons and checkboxes
    private List<AppCompatButton> mButtons = new ArrayList<>();
    private List<CheckBox> mCheckboxes = new ArrayList<>();
    private List<TextView> mTextviews = new ArrayList<>();
    private List<View> mViews = new ArrayList<>();
    //TODO I Added this to hold all the number to items values
    private Map<String, String> numberItemValues = new HashMap<>();
    //Button buttontest;
//TODO this is the item list variable I created as global
    List<String> itemList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        GlobalClass globalClass = (GlobalClass) this.getApplicationContext();


        ArrayList<String> items = new ArrayList<>();
        items.add(String.valueOf(mSpinners)); // add you selected item
        globalClass.setItems(items);


        mSpinners = new ArrayList<>();

        mLinearLayout = findViewById(R.id.my_linearLayout);

        //mLinearLayout.setBackgroundColor(Color.parseColor("#ffffff")); sets colour for whole mlinearLayout so if you want to pess it to elete it'll deelete deverhything .


        //mLinearLayout.addView(makeSpinner());    // First spinner


        //When user clicks the FAB button,  hide the existing layout, using View.GONE,and then create spinner and checkbox
        // programatically(refer to my aligning code) and then programatically set the mLinearLayou background to the bg.xml
        // layouts background = mLinearLayout
        //You can choose which all elements to hide, using their id

        //btn2.setVisibility(View.GONE);
        //take away the white button , .


        //code for the add button to add more items
        FloatingActionButton floatingActionButton =
                (FloatingActionButton) findViewById(R.id.fab);

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();


                // Handle ze click.
                final Spinner spinner = makeSpinner();
                mLinearLayout.addView(spinner);


                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
                layoutParams.setMargins(5, 100, 10, 0); //top 70

                Resources resources = getResources();
                DisplayMetrics metrics = resources.getDisplayMetrics();

                layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
                layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
                spinner.setLayoutParams(layoutParams);

                final View newView = makeView();
                //TODO adds a new view that is suppose to replicate the button so when it is pressed, blah happens.
                //TODO i.e move the button code to the onclick View then delete button cause its useless.
                //Add a new view
                mLinearLayout.addView(newView);

                //TODO create new layout params here



                mViews.add(newView);

                final int listSize = mViews.size();


                //code for deleting the said item.
                newView.setOnClickListener(new View.OnClickListener() {
                    //start
                    @Override
                    public void onClick(View view) {

                        //when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.

                        final View.OnClickListener context = this;


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


                        // 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


                                        if (listSize > 0) {

                                            mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
                                            mSpinners.get(listSize - 1).setVisibility(View.GONE);
                                            mViews.get(listSize - 1).setVisibility(View.GONE);
                                            mTextviews.get(listSize - 1).setVisibility(View.GONE);
                                            Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).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();


                    }
                });




                //Add a new checkbox
                final CheckBox newCheckbox = makeCheckbox();
                mLinearLayout.addView(newCheckbox);

                //TODO add checkbox to your list
                mCheckboxes.add(newCheckbox);



                final TextView newTextview = makeTextview();
                mLinearLayout.addView(newTextview);
                mTextviews.add(newTextview);

            }
        });


    }


    //DUPLICATING ITEMS WHEN FAB IS PRESSED//
    private CheckBox makeCheckbox() {
        //Create new Checkbox
        CheckBox checkbox = new CheckBox(this);

        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        checkbox.setLayoutParams(layoutParams);
        return checkbox;
    }


    private TextView makeTextview() {
        //create new textview
        TextView textview = new TextView(this);

        //setup layout

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textview.setLayoutParams(layoutParams);
        textview.setText("ihi");
        return textview;

    }



    private View makeView() {
        //create new View

        View view = new View(this);
        view.setBackgroundColor(Color.parseColor("#ffffff"));
        LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
        new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
        //LinearLayout.LayoutParams.MATCH_PARENT,
        // LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setClickable(true);




        view.setLayoutParams(layoutParams);


        //setup layout

        return view;


    }






    private Spinner makeSpinner() {
        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
        CSVFile csvFile = new CSVFile(inputStream);
        //TODO I made this variable global, declared it at the very top of this file
        itemList = csvFile.read();

        //Create new spinner
        // SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
        SearchableSpinner spinner = new SearchableSpinner(this);


        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        spinner.setLayoutParams(layoutParams);
        MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);


        spinner.setAdapter(adapter);

        //TODO Add the spinner on item selected listener to get selected items
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                 String currentItem = items.get(position);
                 String aisleNumber = numberItemValues.get(currentItem);
                //TODO you can use the above aisle number to add to your text view
                 textview.setText(aisleNumber);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });


        //Add it to your list of spinners so you can retrieve their data when you click the getSpinner button
        mSpinners.add(spinner);
        return spinner;
    }



    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 hashmap 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;
        }
    }
}

CSV文件:

编号,项目

0,土豆片

0,鸡蛋

0,坚果

0,爆米花

0,餐巾纸

0,Muesli酒吧

0,派对物品

1,茶

1,咖啡

1,喝巧克力

1,米洛

2,能量饮料

2,水

2,软饮料

2,果汁

3,水果罐头

3,甜点

3,价差

3,奶制品

4,谷物

4,饼干

4,饼干

5,墨西哥

5,罐头食品

5,调味

6,意大利面

6,国际食品

6,调味酱

6,米饭

6,汤

6,巧克力

7,泡菜

7,美味

7,Gravies

7,酱汁

7,面条

8,面粉

8,糖

8,烘焙需求

8,保鲜膜

8,沙拉酱

8,草药

8,盐

8,食用油

9,Aircare

9,家用清洁剂

10,宠物

11,洗衣

11,洗碗

12,婴儿需要

13,护肤

14,纸巾

14,洗发水

14,调节器

14,健康与美丽

14,冰淇淋

14,冷冻商品

3 个答案:

答案 0 :(得分:0)

  

当用户从下拉菜单中选择一项时,相应的“数字”(来自csv)会显示在TextView上。

     

这可能吗?关于如何使它正常工作的任何想法?

是的,有可能。您必须执行以下操作:

  • 读取CSV文件
  • 创建一个包含map<item, number>
  • 的数据结构

答案 1 :(得分:0)

您可以创建一个HashMap<item, number>并像这样存储您的值(假设两个值都是字符串值)

HashMap<String, String> resultList =new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
    String line;
    while ((line = reader.readLine()) != null) {
        String[] row = line.split(",");
        resultList.put(row[1],row[0]);
    }
} catch (IOException e) {
    Log.e("Main", e.getMessage());
} finally {
    try {
        inputStream.close();
    } catch (IOException e) {
        Log.e("Main", e.getMessage());
    }
}
return resultList;

这将返回一个HashMap

您可以使用

访问值
for (Map.Entry<String,String> entry : resultList.entrySet()) {
    Toast.makeText("Item : " + entry.getKey() + " Number : " + entry.getValue()).show();
}

如果您仍然想要List<String>项可以创建的项目,请使用上述方法。然后您可以使用HashMap

为该项目获取相应的“数字”
String number = resultList.get(item);

答案 2 :(得分:0)

您更新的create.java活动(我添加了TODO来显示更改的部分):

更新的代码:

a