I have a dialog setup that has two spinners connected to a cursor. I have worked through a couple of problems with the help of this site, but I can not seem to get past this point. Everything I find are things I have already tried.
The problem is that when I click on a spinner selection or click Submit to exit the dialog, the spinner value is not the value it should be. I am getting the package name with some code. I am trying to get the string from the spinner with .getSelectedItem().toString();
I currently have the code set up to use onItemSelected, but before that I tried to use the getItemSelected once Submit was clicked. Neither seem to work.
Here is the code for this section.
At the end the values are going into a textview. The value shown is "android.database.sqlite.sqliteCursor#414175e0"
Any ideas?
private void transfer() {
dialog = new Dialog(this, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
dialog.setContentView(R.layout.transfer_dialog);
dialog.setTitle(R.string.transfer_accounts);
Button btnCancel = (Button)dialog.findViewById(R.id.btnCancel);
Button btnSubmit = (Button)dialog.findViewById(R.id.btnSubmit);
Cursor load_spinner = mDbHelper.spinnerAccounts();
startManagingCursor(load_spinner);
String[] columns = new String[] { RegisterDbAdapter.ACCOUNTS_ACCOUNT };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, load_spinner, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom = (Spinner)dialog.findViewById(R.id.spinnerFrom);
spinnerTo = (Spinner)dialog.findViewById(R.id.spinnerTo);
spinnerFrom.setAdapter(mAdapter);
spinnerTo.setAdapter(mAdapter);
dialog.show();
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
fromAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinnerTo.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
toAccount = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btnSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tvFrom.setText(fromAccount);
tvTo.setText(toAccount);
dialog.dismiss();
}
});
}
You need two separate adapters for two spinners.
You are only using one... each time you make a selection, the adapter sets your selection to your choice ( for both of the spinners since you have the same adapter backing each one ).
Create a second adapter and things should work more like you expect.
Also, try this in your onItemSelected method (using the parameter names you show):
String fromAccount = parent.getItemAtPosition(arg2).toString();
I think you have to use your cursor to get the String you want. Arg2 should be the selected position. Use it to place your cursor to the right data row and use the getstring method of the cursor to get the string from the database column.
So I finally got it to work. Thanks for the suggestions, I really do appreciate them, but they didn't work for me. I am not sure why the code will not return the value, since the way I tried it supposedly works for others.
Anyway, I found a way to get my values by using 'Long arg3'. Since it holds the rowId of the value in the table, I used that to return the selection in the spinner. I am posting the code for this below.
Thanks again.
The code from the selected spinner:
spinnerFrom.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
getAccountName(arg3);
fromAccount = returnAccount;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
And here is the method I wrote to return the value I wanted. I put it a separate method because it is getting used from multiple spinners. The code:
private void getAccountName(long arg3) {
if (returnAccount != null){
returnAccount = null;
}
RegisterDbAdapter tAdaptor = new RegisterDbAdapter(this);
tAdaptor.open();
Cursor tCursor = tAdaptor.fetchAccount(arg3);
startManagingCursor(tCursor);
returnAccount = tCursor.getString(1);
}
Related
I'm creating an Android app in which there is a listeview and the search is filtered through an EditText.
What I want to know is how does Instagram (for example) show the preview of searches divided into categories?
Let me explain better, if on Instagram I look for example "London" I will come out in a list of fields where for example there is the city icon and with the word "London" next to it, underneath there is a field with "#london" written on it and another field with "London" and the user's photo below.
What are the names of the searches divided into categories or sections in "Programming"?
I would like to do it in my App but the problem is that I don't know how to call this thing.
If I have a listview and want to filter it through a search, while I type the word "London" it immediately shows me the Items with the same name as "London", instead I want a search like that of Instagram where the results are filtered first categories and then when you click on the category it shows you the results.
What is the name of this practice?
Use something like:
private ArrayAdapter<String> mAdapter;
private String[] data = {"myname","myname2","myname3","myname4","myname5"};
private EditText searchBox;
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
searchBox = findViewById(R.id.searchBox);
mListView = findViewById(R.id.mListView);
mListView.setTextFilterEnabled(true);
mAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, data);
mListView.setAdapter(mAdapter);
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
MainActivity.this.mAdapter.getFilter().filter(arg0);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
Now if you enter "myname2" in the edittext, ListView will only show it. You can use the similar approach in case of GridView/RecyclerView.
I usually use boolean for this but in this situation I can not. I have a code like below on my Spinner and everything works fine :
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
carNames = brand.getChildCarNames(brand.getListDataHeader().get(position));
makeAndShowDialogBox();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
The problem is when I use bolean what happens is that the choice that comes as Default is not showing the DialogBox if user chooses that Default value as-well. Such as "Tomato" comes as Default and user wants to select "Tomato" as well; nothing happens than.
What I want to do is also prevent this dialog box coming asap when Activity is opened but also I want to prevent "on selection of default value nothing happens" issue.
So, Is there any way to check exactly if the User pressed to select or not?
You can use a Boolean variable to determine if the spinner is just loaded, so you can prevent the dialog to show when the Activity is opened (or onResume). You can declare a variable outside the listener, and change its value inside the listener. Its value is changed inside the listener, so you have to do final Boolean array instead of regular Boolean.
You can try with the following code:
final Boolean[] spinnerLoaded = {false};
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (!spinnerLoaded[0]) {
spinnerLoaded[0] = true;
}
else {
carNames = brand.getChildCarNames(brand.getListDataHeader().get(position));
makeAndShowDialogBox();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
I use Eclipse ADT build:v21.1.0-569685, the Case One is an sample code from website, but it cause the error
"The type new AdapterView.OnItemSelectedListener(){} must implement the inherited abstract method AdapterView.OnItemSelectedListener.onNothingSelected(AdapterView)"
so I have to use the Case Two, but sometimes the Case One is OK, what happened? Thanks!
Case One
private void InitSpinner(){
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
nameList.toArray(new String[nameList.size()]));
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFolder.setAdapter(adapter1);
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this,
"cw", 2000).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
Case Two
private void InitSpinner(){
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
nameList.toArray(new String[nameList.size()]));
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFolder.setAdapter(adapter1);
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(MainActivity.this,
"cw", 2000).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Paul
Does the arguments name must be same?
No, the arguments name need not be same. And as such both codes are exactly identical and will work in same fashion.
Why I get
The type new AdapterView.OnItemSelectedListener(){} must implement the inherited abstract method AdapterView.OnItemSelectedListener.onNothingSelected(AdapterView)
error?
I guess you must have copied that part of code from your other project's or must have copied directly from internet through some site. In here, You have copied the correct syntax, but have not done right imports for the same....
Try..
Ctrl+Shift+O to organise all the essential import required...
Hope it helps.....
In the current Activity I'm printing a graph (using Androidplot) of the closing prices of a selected stock from the previous activity.
In this activity I have a spinner of a list of indicators the user can overlay.
Now I want the graph to be redrawn with this new selection from the spinner.
I did try refreshing/reloading the page onItemSelected but that causes the page to keep refreshing even without waiting for a user input.
public class DispGraph extends Activity {
private XYPlot plotstock;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
// PRINTING SELECTED STOCK_NAME
Bundle bundle = getIntent().getExtras();
String sname = bundle.getString("SN");
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(sname);
// INDICATOR LIST
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.Indicators, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
String iname = spinner.getSelectedItem().toString();
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
startActivity(getIntent());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
//PASSING STOCK-TICKER & INDICATOR TO PHP
// PLOTTING GRAPH
plotstock = (XYPlot) findViewById(R.id.mySimpleXYPlot);
Number[] series1Numbers = ind;
Number[] series2Numbers = closing;
XYSeries series1 = new SimpleXYSeries(Arrays.asList(series1Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, iname);
XYSeries series2 = new SimpleXYSeries(Arrays.asList(series2Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Closing Price");
plotstock.setDomainLabel("Date");
plotstock.setRangeLabel("Price");
plotstock.addSeries(series1,new LineAndPointFormatter(Color.rgb(0, 200, 0), Color.rgb(0,100, 0), null, new PointLabelFormatter(Color.TRANSPARENT)));
plotstock.addSeries(series2,new LineAndPointFormatter(Color.rgb(0, 0, 200), Color.rgb(0, 0, 100),null, new PointLabelFormatter(Color.TRANSPARENT)));
plotstock.setTicksPerRangeLabel(2);
}
}
Using your current approach, each time the user select a spinner value your current activity will be started again, so it will be put on Android Stack. Soon, if the user change your spinner n times, you should press n + 1 times to close your app. This is a really annoying behavior.
Well, I do not know the AndroidPlot, but looking its API I found the method redraw.So, i think you could try on that way:
Every time the user select a spinner value, i can do your modifications on plotstock after call plotstock.redraw()
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
//Change the graphics value here!
plotstock.redraw();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.