I have a drop down AutoCompleteTextView in an action bar.
I am attempting to get text from the AutoCompleteTextView and store it into a string.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location2);//Location2 is my layout
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.location, null);//location is my custom action bar
actionBar.setCustomView(view);
Global global = new Global();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, global.getUniversities());
AutoCompleteTextView textView = (AutoCompleteTextView) view
.findViewById(R.id.searchLocation);
textView.setAdapter(adapter);
...
}
public void changeLocation(View view){
View v = View.inflate(this, R.layout.location, null);
AutoCompleteTextView searchLocation = (AutoCompleteTextView)
v.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
...
}
<AutoCompleteTextView
android:id="#+id/searchLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:drawableLeft="#drawable/search"
android:paddingTop="15dp"
android:imeOptions="actionSearch"
android:inputType="textAutoComplete|textAutoCorrect"
android:textColor="#FFFFFF" >
<requestFocus />
</AutoCompleteTextView>
The autocomplete feature works like a charm... But the toast shows that String searchLocationText is empty...
What is incorrect about the autocompletetextview in the actionbar?
How can I get the text into a string?
Edit:- More details
I am able to type in the AutoCompleteTextView, it autocompletes with a drop down list and everything is working fine. But I try to turn that information into a string and the string is empty...
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.AutoCompleteTextView.getText()' on a null object reference
Error refers to line:
String searchLocationText = searchLocation.getText().toString();
You need to get the text from the view you have attached to your layout. But you're inflating a new view here.
public void changeLocation(View view) {
View v = View.inflate(this, R.layout.location, null);
AutoCompleteTextView searchLocation = (AutoCompleteTextView)
v.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
[...]
}
Instead find the view on the activity like in onCreate()
public void changeLocation(View view) {
ActionBar actionBar = getSupportActionBar();
view = actionBar.getCustomView();
AutoCompleteTextView searchLocation = (AutoCompleteTextView) view
.findViewById(R.id.searchLocation);
String searchLocationText = searchLocation.getText().toString();
Toast.makeText(this, searchLocationText,
Toast.LENGTH_LONG).show();
[...]
}
Related
I'm making a project for university, I have a DialogFragment where I record a new animal for a database. In the form, there is a spinner that is loaded from a database. This is the "onCreate" code of DialogFragment:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_add_animal, null);
Spinner spEspecies = (Spinner) v.findViewById(R.id.spinner);
Cursor c = getActivity().getContentResolver().query(ContratoBBDD.Especies.URI_CONTENIDO,null,null,null,null);
SimpleCursorAdapter adaptador =
new SimpleCursorAdapter(getActivity().getApplicationContext() ,android.R.layout.simple_spinner_item,c,
new String[]{ContratoBBDD.Especies._id},
new int [] {android.R.id.text1},SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER );
Log.d("Tam", c.getCount() + "");
Log.d("Col", c.getColumnCount() + "");
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEspecies.setAdapter(adaptador);
ActionBar actionBar = ((AppCompatActivity) getActivity())
.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDefaultDisplayHomeAsUpEnabled(false);
}
I can see in the log and debugging that the cursor has information, as does the spinner -- but when I click in the spinner, it's empty. Where do I lose the information?
You can look this link
Putting cursor data into an array
//the constructor
Spinner spEspecies = (Spinner) v.findViewById(R.id.spinner);
//set the value to show
//change this line with query, better use ArrayList<String>
String Especies[] = {"Homo Sapiens","Felis Domestica","Zea mays"};
//insert to spinner
ArrayAdapter<String> aaspEspecies = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Especies);
// The drop down view
aaspEspecies.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEspecies.setAdapter(aaspEspecies);
I am trying to populate a a spinner but I am getting an error with my String array saying "Array constants can only be used in initializers". My code works fine when i employ the string array as a local variable, but as a global variable it doesn't. I really need to be able to use my string array as a global variable. Thank you in advance. Here is my code:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
I did the same thing for one of my project and it works for me. Below is the code snippet for your reference..
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
inside string.xml Write:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
Inside your MainActivity.java :
public class MainActivity extends Activity {
Spinner spinner_environment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
Inside spinner_phone.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
try this out. Hope it will help you.
How can I change view of item in drop down navigation list in action bar on click?
After click, I want that displayed item shows another view (in layout it is set as invisible).
I've got onNavigationItemSelected method from ActionBar.OnNavigationListener but it does not pass view of the item clicked but just position of item in navigation spinner. Or in other words, why can I not get reference to selected view from actionbar spinner? (like I can get view with listview onItemClick from OnItemClickListener())
ActionBar's Spinner resource id is : android:id/action_bar_spinner
Get the Spinner resource id:
int resId = getResources().getIdentifier("action_bar_spinner", "id", "android");
Get the reference to Spinner widget using the resource id:
final Spinner spinner = (Spinner) getWindow().getDecorView().findViewById(resId);
Now you will be able to get access to the selected view:
CheckedTextView v = (CheckedTextView) spinner.getSelectedView();
You can modify the selected view right away in OnNavigationListener:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyFragment())
.commit();
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.action_list, android.R.layout.simple_spinner_dropdown_item);
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
int resId = getResources().getIdentifier("action_bar_spinner", "id", "android");
final Spinner spinner = (Spinner) getWindow().getDecorView().findViewById(resId);
this.getActionBar().setListNavigationCallbacks(mSpinnerAdapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
CheckedTextView v = (CheckedTextView) spinner.getSelectedView();
// Modify selected view.
return true;
}
});
}
I was just trying to figure this out and managed to track it down.
Use setSelectedNavigationItem to do this.
With your navigationListener, you can try this :
OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
View convertView = null;
View view = adapter.getView(itemPosition, convertView, null);
TextView myTextView = (TextView) view
.findViewById(R.id.my_textView);
Toast.makeText(getBaseContext(), myTextView.getText(),
Toast.LENGTH_LONG).show();
return true;
}
You are then retrieving the item via the adapter. My only problem is now modifying the retrieved reference content. I can't seem to have it working.
I Hope it helps
I used the HelloTabWidget from here (http://developer.android.com/resources/tutorials/views/hello-tabwidget.html) as a starting point.
Now I edited the onCreate for the first Tab:
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("tab0").setIndicator("Tab0", res.getDrawable(R.drawable.ic_tab_artists));
spec.setContent(new MyTabContentFactory(this, R.layout.tab0));
tabHost.addTab(spec);
MyTabContentFactory:
public class MyTabContentFactory implements TabContentFactory {
private Activity parent = null;
private int layout = -1;
public MyTabContentFactory(Activity parent, int layout) {
this.parent = parent;
this.layout = layout;
}
#Override
public View createTabContent(String tag) {
View inflatedView = View.inflate(parent, layout, null);//using parent.getApplicationContext() threw a android.view.WindowManager$BadTokenException when clicking ob the Spinner.
//initialize spinner
CharSequence array[] = new CharSequence[4];
for (int i = 0; i < array.length; i++) {
array[i] = "Element "+i;
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(parent, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
View view = parent.findViewById(layout);
if(view != null) {
ArrayList<View> touchables = view.getTouchables();
for (View b : touchables) {
if (b instanceof Spinner) {
((Spinner) b).setAdapter(adapter);
}
}
}
return inflatedView;
}
}
tab0.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:id="#+id/entry1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="#string/brand_prompt"
/>
</RelativeLayout>
MyTabContentFactory should initialize the Spinner, but view in createTabContent is always null. Why is that so? How can I find the Spinner in order to initialize it?
This line
View view = parent.findViewById(layout);
means nothing, I see what your trying to do, but it just doesn't work like that. You can't get views off your activity you have to reference the inflated XML view.
I think what your trying to do is this:
ArrayList<View> touchables = inflatedView.getTouchables();
for (View b : touchables) {
if (b instanceof Spinner) {
((Spinner) b).setAdapter(adapter);
}
}
but tbh you don't even need to do that, you should do this:
Spinner spinner = (Spinner) inflatedView.findViewById(R.id.entry1);
spinner.setAdapter(adapter);
Hi i've got a custom listview with a text view and a button in each row.
Im having trouble trying to use the buttons . Each button will fire a different intent. This is the xml file for the list view rows.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
android:id="#+id/widget28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="#+id/widget29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me"
android:layout_alignParentRight="true"
/>
<TextView android:id="#+id/text12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff99ccff"
android:text="Text view" />
</RelativeLayout>
Then i have another xml file which simply contains the list view in a linear layout.
This is my custom array class.
public class customArray extends ArrayAdapter<String> {
int resource;
public customArray(Context cont, int _resource, List<String> items) {
super (cont, _resource,items);
resource = _resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout rl;
String prod = getItem(position);
if (convertView == null) {
rl = new RelativeLayout(getContext());
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(resource, rl, true);
} else {
rl = (RelativeLayout)convertView;
}
TextView t1 = (TextView)rl.findViewById(R.id.text12);
t1.setText(prod);
Button b1 = (Button)rl.findViewById(R.id.widget29);
return rl;
}
}
Then the final class which gets the data from a database and uses the custom adapter to display the information. Does anyone know how i would call each button?
`public class SatMain extends Activity {
/** Called when the activity is first created.
* #param cont */
#Override
public void onCreate(Bundle savedInstanceState)
{
List<String> results = new ArrayList<String>();
super.onCreate(savedInstanceState);
setContentView(R.layout.satmain);
dbAdapter db = new dbAdapter(this);
// button.setOnClickListener(m);
//---get all titles---
db.open();
db.InsertData();
Cursor c = db.getSat1();
if (c.moveToFirst())
{
do {
String pub = c.getString(c.getColumnIndex(db.KEY_Artist));
String pub1 = c.getString(c.getColumnIndex(db.KEY_Time));
results.add(pub + pub1 );
} while (c.moveToNext());
}
db.close();
ListView listProducts;
customArray ca = new customArray(this, R.layout.button, results);
listProducts = (ListView)findViewById(R.id.list1);
listProducts.setAdapter(ca);
ca.notifyDataSetChanged();
}
}`
In the "getView" method of your adapter, you should set an onClick listener for the button. You can do an anonymous class so that you can refer to the contents of the row in the button. I.e, add the following where you get b1 in your example.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create activity based on prod
}
});