Android - Populate a textview from a Spinner item - android

I would like to have my application populate an empty textview with the value that a user selects from a spinner. Currently it seems to work, but it only populates the textview with what I'm guessing is the entire cursor: (android.database.sqlite.SQLiteCursor#4120dd08).
Can someone help me figure out what the issue is? I can post more code if necessary.
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
String stringItem = parent.getItemAtPosition(position).toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});

Try this:
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
TextView objTextView = (TextView) commonDescSpin.getSelectedView();
String stringItem = objTextView.getText().toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});

The method toString() usually has other implementations relating to identifying object instances. If you know that the item in the spinner is without a doubt a string, you could consider performing an explicit cast:
String stringItem = (String)(spinner1.getItemAtPosition(2));
textViewStatus.setText(stringItem);

Related

how to add empty first value and set it as null appcompat Spinner

i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?

Get ID or position of listview text

I have a problem with my Listview with 3 textviews when I use a ClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
...
}
I can't find out which textview is clicked.
And when I use a onClick-Method with
<TextView
android:id="#+id/listview_text3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClickMenge"/>
and
public void onClickMenge(View view) {
...
}
I know which textview is clicked but I canĀ“t get the id (Database-ID).
I read and tried but with no success.
Any ideas?
If I understand your issue here:
If you have data in your database tables, you simply need to create a class like this :
public class ListItem {
//define variables here
private long id;
private String itemName;
//define constructor and getters and setters here;
}
Now, when you provide the data to your adapter, you pass to each object instance an id;
Next, when a user clicks on the item in your list, you use the position provided to you by the onClickListener interface, to get the item from your Adapterthen get the id as you wish!
I hope this makes sense and helps you get the solution!
You can use your Cursor to find the id, using the position that onClickListener returns.
(...)
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String[] column = new String[]{"_id"};
Cursor cursor = db.query("name_of_table", column, null, null, null, null, null, null);
cursor.move(position+1);
long id = cursor.getLong(0);
(...)
You need to connect your database with variable db.
private SQLiteDatabase db;
BDCore xDB = new BDCore(context);
db = xDB.getWritableDatabase();
The int position in the on item click listener is the position of ur text view it starts from 0,1,2,3
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(pos==0)
{
TextView txt = (TextView) findViewById(R.id.text_1);
txt.setText("abc");
}
}
});
Use onClick and position from getView method of your adapter
int itemPosition = -1;
Now set itemPosition in getView method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
itemPosition = position;
}
public void onClickMenge(View view) {
int viewId = view.getId();//ID of text view clicked
//Use itemPosition now
}

Set spinner selected item text

I have a spinner (only relevant parts of code)...
protected void onCreate(Bundle savedInstanceState) {
Spinner to_spinner = (Spinner) findViewById(R.id.to_spinner);
List<Unit> list = myDbHelper.getAllUnits();
SpinnerUnitAdapter tUnitAdapter tUnitAdapter = new SpinnerUnitAdapter(this, android.R.layout.simple_spinner_item, list);
to_spinner.setAdapter(tUnitAdapter);
to_spinner.setOnItemSelectedListener(onItemSelectedListenerTo);
}
with an onItemSelectedListener
AdapterView.OnItemSelectedListener onItemSelectedListenerTo = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// do stuff
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
};
When an item is selected (i.e. where it says: "do stuff"), I would like to set/change the text of the selected spinner item. (Note that this is not the same as setting the spinner position (with setSelection()).
I was thinking of doing this with
tUnitAdapter.getView(position, ?, ?).setText("new text");
Am I on the right track? What to put as second ("convertView") and third ("parent") argument in getView. My spinner adapter looks like:
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
label.setTextColor(Color.BLACK);
label.setTextSize(mContext.getResources().getDimension(R.dimen.list_row_font_size));
label.setGravity(Gravity.CENTER);
label.setText(getItem(position).getName());
return label;
}
}
Am I on the right track?
No. You should do the following steps: (in the onItemSelected method)
Update your model (the array of items you passed to the adapter) so that the item at position index takes the new name.
Issue notifyDataSetChanged on the adapter object. Alternatively, you can do this manually by ((TextView) view).setText(new_name);
Note: In onItemSelected method, adapterView points to your spinner view and view points to the row view just selected.
UPDATE #1
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
((TextView) view).setText("new name");
}
UPDATE #2
For this, you should use Java interface to implement a callback which is called once the dialog is closed.
public void onItemSelected(AdapterView<?> adapterView, final View view, int position, long id) {
Dialog dialog = new MyDialog(context, new MyDialog.OnItemSelectListener(){
#Override
public void onItemSelected(String newName){
((TextView) view).setText(newName);
}
});
dialog.show();
}
And declare interface OnItemSelectListener in your MyDialog class.
You can change the text of spinner when you click each item so you should implement onClickListener
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
...
label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change label text here
// label.setText(...);
}
});
return label;
}
}
Hope this help
I think I found the solution. I can just do:
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
TextView tv = (TextView) adapterView.getSelectedView();
tv.setText("new text");
}

How to Add a extra value to spinner

SOLVED HERE IS THE SOLUTION ANSWER http://www.congdegnu.es/2011/06/02/spinners-en-android-tres-formas-de-poblarlos/
I'm populating a spinner from my sqlite database like this:
Cursor CS = newDB.rawQuery("Select ID AS _id, Name from Schools",null);
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
} while(CS.moveToNext());
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Schools);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
My problem is that I only add an id but how can I add a value to that id so when the value get select I get the id ?
I think that "schools" is an array containing you own class "school".
You could add a propertie which contains the information.
Or you could use a 2 dimensional array.
Than you have to set up your arrayadapter to get the information (getter Method).
Hope it helps
Try Cursor Adapter
or
Take a global variable
Hashmap schoolmap=new Hashmap();
While inserting data to the list also add to Hashmap like this
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
schoolmap.put(CS.getString(CS.getColumnIndex("_id")),CS.getColumnIndex("_id"))
} while(CS.moveToNext());
onSpinner item click get the value like this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String value=((TextView)view).getText();
int id=Integer.parseInt(schoolmap.get(value));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Take a look at using a SimpleCursorAdapter for your spinner instead. Although this has been deprecated since API-11, so you may also want to think about using a LoaderManager with a CursorLoader.
An explanation on how to transition to a LoaderManager and CursorLoader can be found here:
How to transition from managedQuery to LoaderManager/CursorLoader?
I would recommend you start by using the SimpleCursorAdapter, then if confortable enough, move on to the other method.
1) Create an ArrayList<School>
2) Add all your Schools to the Arraylist
3) Create a custom adapter like this:
public class SchoolAdapter extends ArrayAdapter<School>{
public SchoolAdapter(Context ctx, List<School> schools){
super(ctx, 0, schools);
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
TextView tv;
if (convertView == null){
tv = new TextView(getContext());
} else {
tv = (TextView) convertView;
}
tv.setTextSize(16);
final School school = getItem(position);
tv.setText(school.toString());
return tv;
}
}
4) Use this in your activity:
final SchoolAdapter adapter = new SchoolAdapter(this, schools);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
School school = adapter.getItem(pos);
// Do whatever you want with your school
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

How to get spinner string value on android?

I have created a spinner and the items of spinner comes from database. However, When I use
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
typeOFBCard = contactSpinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
When I call this listener and try to pick the chosen string of the spinner i get a reference of the sglite something like:
android.database.sqlite.SQLiteCursor#40535568
This is the return value of typeOfBCard.
However, on the spinner I can see normal string like "Work".
Here is how I initialized the spinner :
contactSpinner = (Spinner) findViewById(R.id.contactSpinner);
mobileText =(EditText) findViewById(R.id.mobileText);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllBusinessCards();
startManagingCursor(cursor);
context =this;
contactSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
How ever on the spinner I can see normal string like "Work"
That is because you configured an Adapter on the Spinner, and the Adapter is pulling data out of the Cursor to display.
How to get spinner string value on android?
There is no "spinner string value". Spinners don't have strings. They have views. Those views might be instances of TextView, or they might be instances of ImageView, or they might be instances of a LinearLayout holding onto a TextView and an ImageView, or...
If you want to get data out of the Cursor, call getString() on the Cursor.
Every row in a spinner is a view but it's also a value/object from your source.
Try
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// Parent == where the click happened.
typeOFBCard = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}

Categories

Resources