Populate Spinner from CSV File using Scanner - android

Using Android (Eclipse) I am trying to read a .csv file and dynamically
populate a Spinner using Scanner. Have tried many methods with the same result.
Emulator shows Spinner but only the last comma and price are populated. Also need to
store all three variables in array and retrive them when Spinner selection is made
in order to populate EditText fields. Any assistance would be greatly appreciated...
Data file records:
4,Aluminum Cans,.55 5,Vehicle with cat convertor,9.00 18,Brass ( Irony Red/Yellow ),.20 1001,Deduction Customer # Look-Up,-2.00
Java:
public class BRprogramActivity extends Activity {
private static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
Button addButton;
Button editButton;
Button sendButton;
//
Spinner array_spinner;
//
// activate soft Keyboard
this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//
// .csv comma separated values file
//
try {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));
//
while (scanner.hasNext()) {
String data = (scanner.next());
String [] values = data.split(",");
item = values[0];
description = values[1];
price = values[2];
//
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item,values);
array_spinner.setAdapter(adapter);
}
scanner.close();
} catch (Exception e) {
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
addButton = (Button) findViewById(R.id.addbutton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "ADD button clicked");
}
});
//
editButton = (Button) findViewById(R.id.editbutton);
editButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "EDIT button clicked");
}
});
//
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "SEND button clicked");
}
});
}
}

If you want to display each row of your CSV on one row in the spinner, try this:
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
list.add(scanner.next());
}
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
array_spinner.setAdapter(adapter);
Though has poor readability for the ordinary user, perhaps you only want to display the description and price:
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
String data = scanner.next();
String [] values = data.split(",");
list.add(values[1] + " $" + values[2]);
}
Your posted method only showed the last CSV line, because you were creating a new ArrayAdapter for each line in the CSV and overriding the previous adapter that you had created.
By storing the Scanner's results in a List and moving the adapter's definition out of the Scanner loop, you should be able to see results like you had hope.
Addition from comments
An OutOfBounds exception with length=2, index=2 suggests that at least one row in your real CSV only has two values (one comma). To help you find that row try this:
if(values.length != 3)
Log.v("Example", "Malformed row: " + data);
else
list.add(values[1] + " $" + values[2]);
Also, I neglected to mention that you are not setting a drop down layout for your Spinner. This will not cause the app to crash, but this creates the standard user interface:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Related

value from dynamic spinner in android? [duplicate]

This question already has answers here:
Android Spinner: Get the selected item change event
(17 answers)
Closed 5 years ago.
I create a table dynamically, and inside the table I create a spinner dynamically. When a user selects a string using the spinner, I want to know what was selected.
the GUI:
the dynamic created spinner:
TextView t7v = new TextView(this);
/**********ADD SPINNER*******/
ArrayList<String> spinnerArray = new ArrayList<String>();
if(tempBranch[i].equals("karmiel")) {
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("batyam");
spinnerArray.add("natbag");
}else if(tempBranch[i].equals("batyam")){
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("karmiel");
spinnerArray.add("natbag");
}else{
spinnerArray.add(" " + tempBranch[i] + " ");
spinnerArray.add("batyam");
spinnerArray.add("karmiel");
}
spinner = new Spinner(this);
spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
tbrow.addView(spinner);
/*********END ADD SPINNER*****/
final Button rowButton2 = new Button(this);// create a new button
//Button OK
rowButton2.setText("OK");
rowButton2.setId(i);//set the number of count
// b.addView(rowButton);
tbrow.addView(rowButton2);
// save a reference to the button for later
myButton[i] = rowButton2;
myButton[i].setOnClickListener(btnClick2(rowButton2));//click the button
the Button when I want receive the value:
private View.OnClickListener btnClick2(final Button button) {//clock button that create dynamic
return new View.OnClickListener(){
public void onClick(View v){
//create array
idEmpl = id[v.getId()];
tmpBranch = spinner.getSelectedItem().toString();//NOT WORK TEMPORARY
String type = "changeTempBranch";
/* ManagerListInBackground managerListInBackground = new ManagerListInBackground(v.getContext());
managerListInBackground.execute(type,idEmpl,tmpBranch);//send the data to valid*/
}
};
}
Try this answer: https://stackoverflow.com/a/1714426/9217218
Then inside the onItemSelected method, add the you can get the string value like this:
String selectedItemTitle = mySpinner.getSelectedItem().toString();
So with help of IdleApps Inc and his link:enter link description here
I solved my problem, that is answer:
enter code here/* Value Spinner */
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
/* Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();*/
tmpBranch = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
tmpBranch = spinner.getSelectedItem().toString();
}
});
/* End of Value Spinner */
that code inside in the build dynamic table, so be careful, that not will work in another place (for me minimum)
thank you to everyone!

Android spinners dynamic data binding

I am new to android , I have an activity with 3 multiple spinners as bellow
Spinner 1:department
Spinner2:semester
Spinner3:subjects
and one button
spinner1 shows the department on select of department it has to display the semester on select of semester it has to display the subject spinner
NOTE:-SUBJECT SPINNER DEPENDS ON THE SELECTION OF SEMESTER SPINNER AS WELL AS DEPARTMENT SPINNER.
something like country, state, city spinners but suggest me some other ideas to do it because i am using string resources to list the items of spinners
Please help me
Try something like this in your activity.
Firstly, make your activity implement AdapterView.OnItemSelectedListener & View.OnClickListener.
private Spinner mDepartmentSpinner;
private Spinner mSemesterSpinner;
private Spinner mSubjectSpinner;
private Button mButton;
// Values to fill first spinner with.
private String[] mDepartments = {
"Department 1",
"Department 2",
"Department 3",
"Department 4",
};
private String[] mSemesters;
private String[] mSubjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// Find the spinners and button, declared in the activity's resource file
mDepartmentSpinner = (Spinner) findViewById(R.id.department_spinner);
mSemesterSpinner = (Spinner) findViewById(R.id.semester_spinner);
mSubjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
mButton = (Button) findViewById(R.id.button);
// Initialise spinner with values, placing them into a textview
mDepartmentSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mDepartments));
// Attach a listener for item selection
departmentSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Work out which spinner was selected
switch (view.getId()) {
case R.id.department_spinner:
// Get the selected item
String selectedDepartment = mDepartments[position];
// Get values to fill the semester spinner with, based on initial selection.
mSemesters = getSemestersFor(selectedDepartment);
// Initialise spinner with values, placing them into a textview
mSemesterSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mSemesters));
// Attach a listener for item selection
mSemesterSpinner.setOnItemSelectedListener(this);
break;
case R.id.semester_spinner:
// Get the selected item
String selectedSemester = mSemesters[position];
// Get values to fill the subject spinner with, based on second spinner selection.
mSubjects = getSubjectsFor(selectedSemester);
// Initialise spinner with values, placing them into a textview
mSubjectSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, subjects));
// Attach a listener for item selection
mSubjectSpinner.setOnItemSelectedListener(this);
break;
case R.id.subject_spinner:
mButton.setOnClickListener(this);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please select an option from each spinner.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
// Go to your new activity, passing the selected subject
Intent intent = new Intent(this, SubjectActivity.class);
intent.putExtra("KEY_SUBJECT", (String) mSubjectSpinner.getSelectedItem());
startActivity(intent);
}
You can get the selected subject in the SubjectActivity like so...
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().getExtras().containsKey("KEY_SUBJECT") {
String subject = getIntent().getExtras().getString("KEY_SUBJECT");
}
}
Code for R.layout.text_view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
You will need to implement the following methods yourself, I don't know your logic!
private String[] getSemestersFor(String department) {
// your code here
}
private String[] getSubjectsFor(String semester) {
// your code here
}

Android Add Listview item dynamically?

i want to add listview item dynamically. i had done this but when i restart the app listview item disappear. How can i save this item permanently to listview. please suggest
public class ChatWithAttorney extends Activity {
ImageView btnBack;
ListView chatList;
EditText etMsg;
Button btnSend;
String msg_to_send;
ArrayAdapter<String> adapter;
ArrayList<String> listMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwithattorny);
btnBack = (ImageView) findViewById(R.id.btnback);
chatList = (ListView) findViewById(R.id.chatList);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSend = (Button) findViewById(R.id.btnSend);
listMsg = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.chat_list_text, R.id.tvSentMsg,listMsg);
chatList.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
msg_to_send = URLEncoder.encode(etMsg.getText().toString(),
"utf-8");
listMsg.add(msg_to_send);
adapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
Put those ArrayList items in a database or SharedPreference and read those items when resuming your activity.
You can use Local database , SharedPreference or Static arraylist for storing the messages
AT the Time of Destroy Serialize the List data.
And Deserilize when Application Starts Again.

Android temp update spinner before it gets values from SQLite

I'm wondering if there is some trick to get the spinner updated from an edittext and onClick, before it gets committed to the database and retrieve from there? The list and the spinnerAdapter are set for retrieving values from database, so I'm aware that this question might be stupid.
I was thinking of this logic: enter some text to edittext, click ok, then temporary update the spinner with this text, before it goes to database, then do some other stuff in the activity and last commit everything to database. When you then close and open your activity again, the temporary value is lost, but the spinner gets populatet with the same value, but this time from database.
here is some code:
public class Vnos extends Activity {
//... some values
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
final List<VnosiDB> spinerItems = datasource.getAllNiz();
final ArrayAdapter<VnosiDB> spinnerAdapter = new ArrayAdapter<VnosiDB>(
this, android.R.layout.simple_spinner_item, spinerItems);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
String nizIzSpinerja = spinner.getItemAtPosition(
spinner.getSelectedItemPosition()).toString();
nizDB = nizIzSpinerja;
// nov niz
novNiz = (TextView) findViewById(R.id.dodaj);
novNiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Vnos.this,
android.R.style.Theme_Holo_Dialog);
dialog.setContentView(R.layout.nov_niz);
TextView okNov = (TextView) dialog.findViewById(R.id.okNovNiz);
okNov.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText inputNiz = (EditText) dialog
.findViewById(R.id.niz);
dialog.dismiss();
nizDB = inputNiz.getText().toString();
spinnerAdapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
// ...some other code...
//...
//.. then, here I commit everything to database...
shrani = (TextView) findViewById(R.id.shrani);
shrani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vnosDB = (int) System.currentTimeMillis();
datasource.createVnos(zacetekDB, razlikaDB, nizDB, deloDB,
postavkaDB, dodatekDB, opisDB, vnosDB);
datasource.close();
Toast test = Toast.makeText(Vnos.this, "Vnos " + deloDB
+ " uspešen!", Toast.LENGTH_LONG);
test.show();
startActivity(new Intent("com.sandpit.jazstudent.URE"));
finish();
}
});
}
}
you are using ArrayAdapter, which is loaded by List<VnosiDB>. I assume that VnosiDB represents a record from the database. Why don't you just put a temporary record in this list when you need it?
List<VnosiDB> spinerItems = new ArrayList<VnosiDB>();
VnosiDB tempRec = new VnosiDB();
//set some values to the properties if you need to
spinnerItems.add(tempRec);
//populate the spinner with the temp record

Spinner delete items

I have developed an application in which i have one edit text value of edit text is entered in spinner on button clicked an the item i select to delete gets deleted but the problem is that when i delete the last item of spinner whole spinner list flushes . i want to delete only selected item(only last item)
My code is as follows :
#Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
///////////////////////////////////////////////////////////////
// grab our UI elements so we can manipulate them (in the case of the
// Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText) findViewById(R.id.newSpinnerItemText);
Button addButton = (Button) findViewById(R.id.AddBtn);
Button clearButton = (Button) findViewById(R.id.ClearBtn);
// //////////////////////////////////////////////////////////////
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
((ArrayAdapter) m_adapterForSpinner)
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// m_adapterForSpinner.add("dummy item");
// //////////////////////////////////////////////////////////////
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// //////////////////////////////////////////////////////////////
// add listener for addButton
private void addNewSpinnerItem() {
Log.v("TAG", "addNewSpinnerItems called");
if (m_addItemText.getText().length() == 0) {// ||(m_addItemText.getText().toString()==
// " ")){
Log.v("In if cndtn", "textHolder is of length 0");
Toast.makeText(getApplicationContext(), "The textView is empty",
Toast.LENGTH_LONG).show();
//m_myDynamicSpinner.clearFocus();
//m_myDynamicSpinner.setFocusable(false);
//m_addItemText.setFocusable(true);
} else {
CharSequence textHolder = "" + m_addItemText.getText();
// else{
Log.v("else", textHolder + "");
// m_adapterForSpinner.add(textHolder);
// }
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
// m_adapterForSpinner.clear();
Log.v("TAG", "clearSpinnerItems called");
m_myDynamicSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// TODO Auto-generated method stub
Log.v("TAG", "Itemseleted to be removed is "
+ m_adapterForSpinner.getItem(pos).toString());
Log.v("Position of item", pos + "");
Object t = m_adapterForSpinner.getItem(pos);
Log.v("Object t ", (String) t);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.v("Item removed", t + "");
// m_myDynamicSpinner.setSelected(false);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// m_adapterForSpinner.add("dummy item");
}
for delete all items use:
mySpinner.setAdapter(null);
if you want to delete a particular item, remove this from m_adapterForSpinner and then:
mySpinner.setAdapter(m_adapterForSpinner);
Remember: methods "remove" and "clear" do not work with ArrayAdapter for Android 2.3.3 and lower. You'll receive error message "Unsupported operation.... bla bla bla". May be they work with Android 4.0 and up, I don't know.
Here is my solution which works even with minSdkVersion="5".
Create Spinner and fill it with test data
This code is in an activity form. Use ArrayList as data source for ArrayAdapter instead of array. It's important because you'll use its "remove" method later
List<String> reportFiles = new ArrayList<String>();
//fill some test data
reportFiles.add("aaaaaaaaaaaaa");
reportFiles.add("bbbbbbbbbbbbb");
reportFiles.add("ccccccccccccc");
//create spinner from corresponding layout xml file
Spinner spnReport = (Spinner) findViewById(R.id.spinner_report);
//create ArrayAdapter
ArrayAdapter reportAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, reportFiles);
//set adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item in adapter - is not obligatory
spnReport.setSelection(0);
Remove selected item from Spinner
reportFiles.remove((String)spnReport.getSelectedItem());
//create new ArrayAdapter with modified ArrayList
reportAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,reportFiles);
//set new array adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item
spnReport.setSelection(0);
For me the accepted answer throwed an exception so what I did was this.
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, Collections.emptyList());
spinner.setAdapter(adapter);
I had the same problem. Doing this did solve the problem, by emptying the spinner:
mySpinner.setSelection(Adapter.NO_SELECTION);

Categories

Resources