Monday, August 20, 2018

how to access part of my csv file - android

Leave a Comment

I followed a tutorial on how to link a csv file I have to android studio so I can view one row of the elements from the csv in a dropdown. (The left row is for 'number' and the right row is for 'items'.

but now I'm trying to figure out so that:

When the user selects an item from the dropdown, the corressponding 'number' (from the csv) shows up, on a TextView.

Is this possible? Any ideas on how to get this working?

Thanks!

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<View> mViews = new ArrayList<>();     //Button buttontest;       @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);                   //Add a new button                 final AppCompatButton newButton = makeButton();                 mLinearLayout.addView(newButton);      // Add another button                 //TODO add button to the list                 mButtons.add(newButton);                 final int listSize = mButtons.size();                   //code for deleting the said item.                 newButton.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) {                                              mButtons.get(listSize - 1).setVisibility(View.GONE);                                             mCheckboxes.get(listSize - 1).setVisibility(View.GONE);                                             mSpinners.get(listSize - 1).setVisibility(View.GONE);                                             mViews.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();                       }                 });                  //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                 final View newView = makeView();                 mLinearLayout.addView(newView);                 //TODO create new layout params here                    mViews.add(newView);                   //Add a new checkbox                 final CheckBox newCheckbox = makeCheckbox();                 mLinearLayout.addView(newCheckbox);                  //TODO add checkbox to your list                 mCheckboxes.add(newCheckbox);              }         });       }   //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 View makeView() {         //create new View          View view = new View(this);         view.setBackgroundColor(Color.parseColor("#FFC0CB"));         LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 50);         new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);                 //LinearLayout.LayoutParams.MATCH_PARENT,                // LinearLayout.LayoutParams.WRAP_CONTENT);             view.setLayoutParams(layoutParams);           //setup layout          return view;       }        private AppCompatButton makeButton() { //creates new buttons i need         //Create new Button         AppCompatButton button = new AppCompatButton(this);           // Setup layout         LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         button.setBackgroundColor(Color.parseColor("#ffffff"));           return button;     }       private Spinner makeSpinner() {         //opens csv         InputStream inputStream = getResources().openRawResource(R.raw.shopitems);         CSVFile csvFile = new CSVFile(inputStream);         List<String> 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(",");                      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 Answers

Answers 1

When the user selects an item from the dropdown, the corressponding 'number' (from the csv) shows up, on a TextView.

Is this possible? Any ideas on how to get this working?

Yes, it is possible. You have to do the following :

  • read the CSV file
  • create a data structure containing a map<item, number>

Answers 2

You can create a HashMap<item, number> and store your values like this (Assuming both values are string values)

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; 

This will return a HashMap

You can access the values using

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

if you still want a List<String> of items you can create is using the above method. and you can get the corresponding 'number' to the item using the HashMap

String number = resultList.get(item); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment