如何访问我的部分 CSV 文件 - 安卓



我遵循了有关如何将 csv 文件链接到 android 工作室的教程,以便我可以在下拉列表中查看 csv 中的一行元素。(左行用于"数字",右行用于"项目"。

但现在我试图弄清楚:

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

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

谢谢!

我的列表适配器.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,空气护理

9,家用清洁剂

10,宠物用品

11,洗衣

11,洗碗

12,宝宝需求

13、护肤

14、纸巾

14,洗发水

14,护发素

14、健康美容

14、冰淇淋

14,冷冻货物

您更新的创建.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);
//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;
}
}
}

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

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

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

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

您可以创建一个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;

这将返回一个哈希映射

您可以使用以下方法访问这些值

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

最新更新