hello I try to put in my java Code a Spinner, but it shows in the else if statement error:
private EditText textName;
private EditText textContent;
private Spinner CategorySpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text);
configureButton1();
configureButton2();
textName = (EditText) findViewById(R.id.editTextName);
textContent = (EditText) findViewById(R.id.editContent);
CategorySpinner = (Spinner) findViewById(R.id.editCategorySpinner);
}
private void configureButton1() {
Button del = (Button)findViewById(R.id.btNewText);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), StartActivity.class);
v.getContext().startActivity(myIntent);
}
});
}
private void configureButton2() {
Button save = (Button) findViewById(R.id.btSave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.getText().length() == 0) {
textName.requestFocus();
return;
} else if (textContent.getText().length() == 0) {
textContent.requestFocus();
return;
} else if (CategorySpinner.**getText**().length() == 0) {
CategorySpinner.requestFocus();
return;
} else {
//next Step: get the mood
Intent myIntent = new Intent(v.getContext(), Activity2.class);
myIntent.putExtra("textName", textName.getText().toString());
myIntent.putExtra("textContent", textContent.getText().toString());
myIntent.putExtra("CategorySpinner", CategorySpinner.**getText()**.toString());
v.getContext().startActivity(myIntent);
}
}
}
});
}
it shows in the CategorySpinner.getText() an error. I hope you can help me.
I´ve tried a lot, but not found a solution.
private void initSpinnerList() {
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(listner);
categories = new ArrayList<String>();
categories.add("S");
categories.add("T");
categories.add("U");
categories.add("V");
categories.add("W");
categories.add("X");
categories.add("Y");
categories.add("Z");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
private OnItemSelectedListener listner = new OnItemSelectedListener() {
/*
* (non-Javadoc)
*
* #see
* android.widget.AdapterView.OnItemSelectedListener#onItemSelected(
* android .widget.AdapterView, android.view.View, int, long)
*/
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String item = parent.getItemAtPosition(position).toString();
/// on item selected data
}
/*
* (non-Javadoc)
*
* #see
* android.widget.AdapterView.OnItemSelectedListener#onNothingSelected
* (android .widget.AdapterView)
*/
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onClick(View v) {
if (spinner != null && categories != null) {
Log.v("Selected Spinner Item ",
categories.get(spinner.getSelectedItemPosition()));
}
}
You haven't provided adapter to spinner. please use below code for adapter:
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
after that if u want text of an item than use below code:
String value = spinnerArray[spinner.getSelectedItemPosition()];
which will return value of selected item in spinner. Default it is 0.
Related
The spinner has an array list of band genres when selecting any of the genres in the spinner it will display a toast, the toast isn't showing when clicking the spinner, the code isn't showing any errors ? any ideas why ?
String spinnerSelection = null;
Spinner spinner = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, spinnerContent);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onItemSelected(AdapterView<?>parent, View v, int position, long id) {
{
Toast.makeText( getBaseContext(),"Hell Yeah", Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Don't forget to add click listener in the spinner
spinner.setOnItemClickListener(this);
You are adding setOnClickListener() on your button. Add setOnItemClickListener() to your spinner.
You need to put #Override for onItemSelected(...) and onNothingSelected(...) functions.
Make sure you set a listener on the spinner:
spinner.setOnItemClickListener(this);
Edit
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
MediaPlayer myMusic;
int paused;
public void play(View view) {
if (myMusic == null) {
myMusic = MediaPlayer.create( this, R.raw.fast_and_cold );
myMusic.start();
}
}
public void stop(View view) {
myMusic.reset();
myMusic = null;
}
String spinnerSelection = null;
Spinner spinner = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
final List<String> spinnerContent = new ArrayList<>();
spinnerContent.add("Black Metal");
spinnerContent.add("Death Metal");
spinnerContent.add("Thrash Metal");
spinnerContent.add("Heavy Metal");
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, spinnerContent);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this); // add this line
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
}
#Override // add this line
public void onItemSelected(AdapterView<?>parent, View v, int position, long id) {
Toast.makeText( getBaseContext(),"Show your Devil Horns !!", Toast.LENGTH_SHORT).show();
}
#Override // add this line
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Mainactivity.java
this is the mainactivity which calls the three methods
public class MainActivity extends Activity {
Button b = (Button) findViewById(R.id.button);
public TextView t = (TextView) findViewById(R.id.postp);
public Spinner catspinner,planspinner1,planspinner2;
protected void onCreate(Bundle mbfSplash) {
super.onCreate(mbfSplash);
setContentView(R.layout.activity_main);
chooseCategory();
chooseone();
choosetwo();
}
public void chooseCategory() {
catspinner = (Spinner) findViewById(R.id.catspinner);
ArrayAdapter<CharSequence> catAdapter = ArrayAdapter.createFromResource(this, R.array.states_array, android.R.layout.simple_spinner_item);
catAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catspinner.setAdapter(catAdapter);
catspinner.setOnItemSelectedListener(new planOnClickListener());
}
private void chooseone(){
planspinner1 = (Spinner) findViewById(R.id.planspinner);
List<String> planlist = new ArrayList<String>();
planlist.add("Mandu");
planlist.add("Chanderi");
planlist.add("Jabalpur");
planlist.add("Orccha");
planlist.add("Bhopal");
ArrayAdapter<String> planAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, planlist);
planAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
planspinner1.setAdapter(planAdapter1);
}
private void choosetwo(){
planspinner2 = (Spinner) findViewById(R.id.planspinner);
List<String> planlist1 = new ArrayList<String>();
planlist1.add("Premier Plan");
planlist1.add("The Executive Plan");
planlist1.add("Business Circle Plan");
planlist1.add("Business Diamond Plan");
ArrayAdapter<String> planAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, planlist1);
planAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
planspinner2.setAdapter(planAdapter2);
}
public class planOnClickListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
final int p = pos;
parent.getItemAtPosition(pos);
if (pos==0){
choosePersonalPlan();
}else if (pos==1){
chooseLargeBusPlan();
} else if (pos==2){
chooseSmallMedPlan();
}
/*Intent intent = new Intent(new Intent("com.example.android.testing.SecondActivity"));
intent.putExtra("value",str);
//---set the data to pass back---
//data.setData(Uri.parse(str));
//setResult(RESULT_OK, data);
//---closes the activity---
//finish();
startActivity(intent);*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
the choosecategory() method gives a selected item from spinner
the next method are choosed on the basis of the first spinner item(i.e. second spinner is dependent on the spinner no. one)
second method maybe choose 1 or choose 2
the method is choosen by the help of the onItemSelected method in the planOnClickListener
thanks for the help...
Just pass your extra to your intent
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key","value");
startActivity(intent);
I'm trying to pass the strings "año" and "artista" from two spinners to the next activity and I get the value "año" but "artista" is always void. I used this method to get the values in other activity and there it works but here, "artista" is always void. Moreover, I have tried with switch method and without success.
I hope someone helps me and tells me what I'm doing wrong. I read and look for information before ask for help,
This is my code,
public class Buscar extends Activity implements OnItemSelectedListener{
String año;
String artista;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buscar);
Buscar();
Spinner spinnerBuscarAño = (Spinner) findViewById(R.id.añoSpinner);
String[] añoBuscar = {"1995", "2000", "2005"};
spinnerBuscarAño.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, añoBuscar));
spinnerBuscarAño.setOnItemSelectedListener(this);
Spinner spinnerBuscarArtista = (Spinner) findViewById(R.id.artistaSpinner);
String[] artistaBuscar = {"Michael Jackson", "U2", "Depeche Mode"};
spinnerBuscarArtista.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, artistaBuscar));
spinnerBuscarArtista.setOnItemSelectedListener(this);
}
/*
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
switch (parent.getId()) {
case R.id.añoSpinner:
año = parent.getItemAtPosition(pos).toString();
break;
case R.id.artistaSpinner:
artista = parent.getItemAtPosition(pos).toString();
break;
default:
break;
}
}
*/
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id){
// TODO Auto-generated method stub
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.añoSpinner)
{
año = parent.getItemAtPosition(position).toString();
}
else if(spinner.getId() == R.id.artistaSpinner)
{
artista = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void Buscar() {
Button buttonBuscar = (Button) findViewById(R.id.buscar);
buttonBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),artista, Toast.LENGTH_SHORT).show();
Intent intentBuscar = new Intent(Buscar.this, ListadoMusica.class);
intentBuscar.putExtra("myaño", año);
intentBuscar.putExtra("myartista", artista);
startActivity(intentBuscar);
}
});
}
}
If someone can help me,
Thanks in advance,
Possibly you are trying to catch a string of intent with another name.
Try this code:
SpinnerTest.java
public class SpinnerTest extends Activity implements AdapterView.OnItemSelectedListener {
String year;
String artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_activity);
Spinner spinnerYear = (Spinner) findViewById(R.id.spinner1);
final String[] years = {"1995", "2000", "2005"};
spinnerYear.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, years));
spinnerYear.setOnItemSelectedListener(this);
Spinner spinnerArtists = (Spinner) findViewById(R.id.spinner2);
final String[] artists = {"Michael Jackson", "U2", "Depeche Mode"};
spinnerArtists.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, artists));
spinnerArtists.setOnItemSelectedListener(this);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent searchIntent = new Intent(SpinnerTest.this, SearchActivity.class);
searchIntent.putExtra("year", year);
searchIntent.putExtra("artist", artist);
startActivity(searchIntent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()){
case R.id.spinner1:
year = adapterView.getSelectedItem().toString();
Toast.makeText(SpinnerTest.this, year, Toast.LENGTH_LONG).show();
break;
case R.id.spinner2:
artist = adapterView.getSelectedItem().toString();
Toast.makeText(SpinnerTest.this, artist, Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
SearchActivity.java:
public class SearchActivity extends ActionBarActivity {
String year;
String artist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_spinner_value);
TextView txtYear = (TextView) findViewById(R.id.txtYear);
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
if(getIntent().hasExtra("year")){
year = getIntent().getStringExtra("year");
txtYear.setText(year);
}
if(getIntent().hasExtra("artist")){
artist = getIntent().getStringExtra("artist");
txtArtist.setText(artist);
}
}
}
It works for me
I was tried to retrieve data from database based selected item on spinner.
Here is my database structure
Here is my Activity:
public class help_activity extends Activity implements OnClickListener{
Spinner spinner1;
SQLiteConnector sqlConnect;
ListView lvUsers;
Button b1;
String colors[] = {"Bristleback","Sven","Tiny","Undying", "Naix","Weaver","Spectre","Lich"};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_help);
spinner1 = (Spinner) findViewById(R.id.spinner1);
lvUsers = (ListView) findViewById(R.id.listView1);
b1 = (Button) findViewById(R.id.btn1);
sqlConnect = new SQLiteConnector(this);
addListenerOnSpinnerItemSelection();
final String nameSelected = spinner1.getSelectedItem().toString();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, sqlConnect.getAllRecord(nameSelected));
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (nameSelected.equals("Bristleback")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Sven")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Tiny")) {
lvUsers.setAdapter(adapter);
}
else if (nameSelected.equals("Undying")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Naix")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Weaver")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Spectre")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Lich")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// TODO Auto-generated method stub
}
});
}
public void addListenerOnSpinnerItemSelection() {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item,colors );
spinner1.setAdapter(spinnerArrayAdapter);
}
#Override
public void onClick(View v) {
}
}
And this my method to retrieve data from database:
public List<String> getAllRecord(String nameSelected) {
List<String> namagambar = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_RECORD + " WHERE "
+ HERO_NAME + "=?";
database = dbHelper.getReadableDatabase();
cursor = database.rawQuery(selectQuery, new String[]{nameSelected});
if (cursor.moveToFirst()) {
do {
namagambar.add(cursor.getString(1));
} while (cursor.moveToNext());
}
database.close();
return namagambar;
}
So, when user selected an item on spinner, then the data at nama_hero will showed at listview based on the selected name hero on spinner. But when i running my code, it just showed the top of data on the database
So when i selected name Sven on spinner, the name that showed on listview not "sven" but "bristleback". And it happened also when I choose other hero name.
I think my method to get the name of the selected item in the spinner does not work
Please help me to fix this problem.
SOLVED !!!
Done !!
I already solved this problem, thanks stackoverflow
I change my setOnclickListener become like this b1.setOnClickListener(this);
And move all the items that were in previous to:
public void onClick(View v) {
}
Try to get selected item inside ClickListener
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String nameSelected = spinner1.getSelectedItem().toString();
here I have a Fragment, I use this code and everything works normally, and what I want to do is update my shown list if there is a new file, could you guys give any advice or hint?
CODE:
public class HomeFragment extends Fragment {
public static final String TITLE = "title";
private List<String> library = new ArrayList<String>();
private TextView tv;
private ListView lv;
private ArrayAdapter<String> adapter;
public static Handler handHF;
private String[] temp;
private Object UIlock = new Object();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container,
false);
library = getLibraryList();
if (!library.isEmpty()) {
if (tv != null) {
tv.setVisibility(View.GONE);
} else {
temp = library.toArray(new String[library.size()]);
lv = (ListView) rootView.findViewById(R.id.library_list);
adapter = new ArrayAdapter<String>(rootView.getContext(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
setListener(lv);
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setVisibility(View.GONE);
tv = null;
}
} else {
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setText("No Manga found...");
}
return rootView;
}
#SuppressLint("HandlerLeak")
#Override
public void onResume() {
/*
* Fragment on pause state
*/
super.onResume();
handHF = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
refreshAdapter();
}
}
};
}
private void setListener(ListView lv) {
/*
* Sets listener on listView
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
ChapterActivity.class);
myIntent.putExtra(TITLE, parent.getItemAtPosition(position)
.toString());
startActivity(myIntent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
return true;
}
});
}
private final List<String> getLibraryList() {
/*
* Returns List<String> of library
*/
List<String> l = new ArrayList<String>();
File dir = new File(Constants.UNDUH);
if (dir.exists()) {
File[] dirs = dir.listFiles();
for (File i : dirs) {
l.add(i.getName());
}
return l;
} else {
return l;
}
}
private void refreshAdapter() {
/*
* It will update library and
*/
synchronized (UIlock) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (tv != null) {
tv.setVisibility(View.GONE);
}
library = getLibraryList();
temp = library.toArray(new String[library.size()]);
lv = (ListView) getActivity().findViewById(
R.id.library_list);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
}
});
}
}
}
any advice will be appreciated, thank you!
Update your list of string which you are passing to the ListView in your case you are using
private String[] temp;
Use notifyDataSetChanged Method, just call this after your adapter and it will automatically adds more items to list if your temp[] increments.
like this
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
Where you are adding more data into temp[]
add an extra line
((ArrayAdapter) lv.getAdapter()).notifyDataSetChanged();