【问题标题】:how to access part of my csv file - android如何访问我的 csv 文件的一部分 - android
【发布时间】:2018-08-10 05:19:38
【问题描述】:

我遵循了一个关于如何将我必须的 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;
        }

    }


}

创建.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,麦片条

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,肉汁

7、酱料

7、面条

8、面粉

8,糖

8、烘焙需求

8,食品包装

8、沙拉酱

8、草药

8,盐

8、食用油

9,Aircare

9、家庭清洁工

10、宠物用品

11,洗衣

11,洗碗

12、宝宝需要

13、护肤

14,组织

14、洗发水

14、护发素

14、健康与美丽

14、冰淇淋

14、冷冻商品

【问题讨论】:

  • 这取决于你做了什么
  • 我的意思是您已经实现了将一些值从 CSV 读取到下拉列表中。所以展示你是如何做到的
  • 您的 csv 只有 1 个文件? fab 按钮触发新元素(复选框、按钮、edittext 和微调器)是真的吗?你的 csv 应该只读取一次csvFile.read() 如果只有单个文件,存储为全局数组列表,在你的适配器中设置微调器动作侦听器,我认为这应该是有道理的,你怎么看?
  • 可以发布csv文件吗?
  • 当然我们可以解决,所以 TextView 将显示多个项目。 @Magic_Whizz

标签: android csv


【解决方案1】:

您更新后的 create.java Activity(我添加了 TODO 以显示我更改的部分):

更新代码:

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);

            //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
                    mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
                }

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

            });


        }
    });


}


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



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

【讨论】:

  • 查看讨论
  • 查看讨论 - 我也更新了帖子中的代码 :)
【解决方案2】:

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

这可能吗?关于如何让它发挥作用的任何想法?

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

  • 读取 CSV 文件
  • 创建一个包含map&lt;item, number&gt;的数据结构

【讨论】:

  • 我已经从 csv 文件中为我的下拉列表读取了项目,我该如何为 textview 实现相同的功能?我可以使用我目前拥有的相同代码来执行此操作吗?
  • 现在有什么问题?您想根据 Spinner 选择更改 TextView 的内容?
  • 好的。您成功地用第一列的名称填充下拉列表,对吗?要显示相应的数字,您必须构建一个map&lt;String, Int&gt;,其中键是名称,值是数字。然后,当您从下拉列表中选择一个名称时,您可以在地图中找到相应的值并将其显示在 TextView 中
  • 嗯...here for example。请参阅put() method 填写您的地图,查看get() one 检索数据
  • 您是要我们做这项工作吗? ;-) 很抱歉,但我认为没有比您更能搜索的了...尝试实施它,不要惊慌,如果有问题,请回来
【解决方案3】:

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

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&lt;String&gt; 的项目,您可以使用上述方法创建。并且您可以使用HashMap 获取项目对应的“编号”

String number = resultList.get(item);

【讨论】:

  • 这会进入 mylistadapter 类还是创建类?我假设创建类?
  • 是的。在创建类中。如果需要,您可以将 HashMap 存储在全局类中。 Global Class 。并在您的应用中的任何位置使用它
  • 我几乎已经有了那个代码。除了没有哈希图。
  • 是的。我将HashMap 应用于您发布的代码。您已使用List 仅存储项目。要访问相应的号码,您可以使用此HashMap 方法。并使用Globalclass 存储HashMap,以便您可以从代码中的任何类或适配器访问它。
  • 我替换了它,但我收到了诸如意外令牌之类的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2023-01-05
相关资源
最近更新 更多