So I have been trying to display a list of data from my local mysql server using API calls like getAll,getByID,etc. on the spinner in a drop down style. However when I click on the spinner nothing happens. Here's my code for the passing the data to the spinner:-
public class markAbsentee extends AppCompatActivity implements OnItemSelectedListener{
Button fromDate, toDate, save;
TextView displayFDate, displayTDate;
Spinner genieS;
List genieList;
private Spinner getGenieS;
private List<Genie> getGenieList;
private Button getFromDate;
private Button getToDate;
private Button getSave;
private TextView getDisplayFDate;
private TextView getDisplayTDate;
private DatePickerDialog.OnDateSetListener mDateSetListener, mDateSetListener1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_absentee);
getGenieS = (Spinner) findViewById(R.id.geniespinner);
getFromDate = (Button) findViewById(R.id.button2);
getToDate = (Button) findViewById(R.id.button3);
getDisplayFDate = (TextView) findViewById(R.id.fromDate);
getDisplayTDate = (TextView) findViewById(R.id.toDate);
new SpinTask().execute();
//I have called the AsyncTask here which contains the get() API
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Genie selected = (Genie)parent.getSelectedItem();
Toast.makeText(markAbsentee.this, selected.id + " " + selected.name, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class SpinTask extends AsyncTask<Void, Void, List<Genie>>{
private Exception exception;
protected void onPreExecute(){}
#Override
protected List<Genie> doInBackground(Void... voids) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostexecute(List<Genie> genies){
if(genies == null){
new ArrayList<Genie>();
}else {
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
ArrayAdapter<Genie> adapter = new ArrayAdapter<Genie>(markAbsentee.this, android.R.layout.simple_spinner_item, genies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Toast.makeText(markAbsentee.this, "Clicked", Toast.LENGTH_LONG).show();
genieS.setAdapter(adapter);
}
}
private String getRow(Genie g){
return String.format("%s %s", g.name, g.salary);
}
}
}
Here's the layout of the spinner:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bcak"
android:orientation="vertical"
tools:context="com.codionics.geniem.markAbsentee">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="76dp"
android:layout_marginTop="59dp"
android:text="Enter Absentee"
android:textSize="30dp"
android:textColor="#ffff" />
<Spinner
android:id="#+id/geniespinner"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView4"
android:layout_marginStart="20dp"
android:layout_marginTop="27dp"
android:popupBackground="#color/colorPrimary"
android:spinnerMode="dropdown"
android:autofillHints="Select genie" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
P.S:- GenieService is the service class for calling the API's. I want to display the name and salary of the person in the spinner drop down list.Thanks in advance for the help.
when you set spinner value it containg only single value like string,integer etc show. when you getting data then it add data into list like below ...
listArray.addAll("Your Value");
then after define array adapter like below and set spinner ..
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(arrayAdapter);
then after you called any function on spinner item selection used like below code ...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Hello",0).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Related
I am writing the basic task management application. I am using base adapter to work with ListView. I wonder how I can remove (a few) checked values from the list? And how I can remove only one value with long click?
if this posible with my adapter? I tried a few options but nothing worked.
Here is my code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:text="\u2713"
android:background="#drawable/add_btn"
android:onClick="knopka2"/>
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/btn1"
android:hint="put your task here"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:divider="#drawable/deriver"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice" />
<TextView
android:id="#+id/ttl"
android:layout_below="#id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/tryClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/ttl"
android:onClick="tryClear"
/>
</RelativeLayout>
This is my Activity:
public class Trird extends AppCompatActivity {
Button btn;
EditText input4;
TextView ttl;
ListView list;
public static ArrayList<String> taskList = new ArrayList<String>();
SparseBooleanArray sparseBooleanArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
input4 = (EditText) findViewById(R.id.input);
btn = (Button) findViewById(R.id.btn1);
list = (ListView) findViewById(R.id.listView);
ttl = (TextView)findViewById(R.id.ttl);
}
public String[] putToArray() {
String ag = input4.getText().toString().trim();
if (ag.length() != 0) {
taskList.add(ag);
input4.setText("");
}
String[] abc = taskList.toArray(new String[taskList.size()]);
return abc;
}
public void knopka2(View v) {
final String[] ListViewItems = putToArray(); //
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new MyAdapter(ListViewItems, this));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View tv, int i, long id) {
///tv.setBackgroundColor(Color.YELLOW);
///ttl.setText("selected: " + list.getAdapter().getItem(i));
sparseBooleanArray = list.getCheckedItemPositions();
String ValueHolder = "";
int a = 0;
while (a < sparseBooleanArray.size()) {
if (sparseBooleanArray.valueAt(a)) {
ValueHolder += ListViewItems[sparseBooleanArray.keyAt(a)] + ",";
}
a++;
}
ValueHolder = ValueHolder.replaceAll("(,)*$", "");
Toast.makeText(Trird.this, "ListView Selected Values = " + ValueHolder, Toast.LENGTH_LONG).show();
if(ValueHolder!=null){
taskList.remove(ValueHolder);
}
}
});
}
}
This is my adapter:
public class MyAdapter extends BaseAdapter {
private final Context context;//Context for view creation
private final String[] data;//raw data
public MyAdapter(String[] data, Context context){
this.data=data;
this.context=context;
}
//how many views to create
public int getCount() {
return data.length;
}
//item by index (position)
public Object getItem(int i) {
return data[i];
}
//ID => index of given item
public long getItemId(int i) {
return i;
}
//called .getCount() times - for each View of item in data
public View getView(int i, View recycleView, ViewGroup parent) {
if(recycleView==null)recycleView = LayoutInflater.from(context).inflate(R.layout.item,null);
((TextView)recycleView).setText(data[i]);//show relevant text in reused view
return recycleView;
}
}
And this is how looks like item in ListView.
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
/>
The problem is that you are trying removing item using the ListView remove methode.
Just remove the selected item from the list using the remove() method of your Adapter.
A possible way to do that would be:
CheckedTextView checkedText= baseAdapter.getItem([POSITION OF THE SELECTED ITEM]);
baseAdapter.remove(checkedText);
baseAdapter.notifyDataSetChanged();
put this code inside the wanted button click and there you go.
I am having trouble with the variable: URL_STRING. I can't seem to add a value from another variable to URL_String. It just null for some reason. Your assistance would be appreciated.
public class HomeScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
ListView listView;
Spinner spinner;
EditText search;
Button bt;
String URL_STRING;
String entity;
String term;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView) findViewById(R.id.listView);
spinner = (Spinner) findViewById(R.id.spinner);
search = (EditText) findViewById(R.id.search);
term = search.getText().toString();
bt = (Button) findViewById(R.id.searchBtn);
ArrayAdapter<CharSequence> entityAdapter = ArrayAdapter
.createFromResource(this, R.array.Entities,
android.R.layout.simple_spinner_item);
spinner.setAdapter(entityAdapter);
spinner.setOnItemSelectedListener(this);
}
This is where I am having trouble. URL_STRING is still null
public void addURL(View view) {
if(entity == "Select" && term != null){
URL_STRING = String.format(getResources().getString(R.string.url1),term);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}else if(term == null){
Toast.makeText(getApplicationContext(), "Please enter a search term",
Toast.LENGTH_LONG).show();
}else{
URL_STRING = String.format(getResources().getString(R.string.url2), term, entity);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
entity = String.valueOf(spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
entity = null;
}
}
I am not very sure about the adapter and the array being assigned to it.
I have created something which are looking for, Kindly try this, code is available on Github as well have a look at it if i may have missed something. to load the imgae I am using a library called picasso which you can easily import by adding following code to the dependencies block in the build.gradle file like this
compile 'com.squareup.picasso:picasso:2.5.2'
and you would be able to use picasso
public class SpinnerTestTwoActivity extends Activity {
private Spinner url_Spinner;
private Button load_image_Button;
private ImageView url_image_ImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test_two);
initializeUI();
}
private void initializeUI() {
url_Spinner = (Spinner) findViewById(R.id.SpinnerTestTwoActivity_url_spinner);
load_image_Button = (Button) findViewById(R.id.SpinnerTestTwoActivity_load_image_button);
url_image_ImageView = (ImageView) findViewById(R.id.SpinnerTestTwoActivity_image_from_url_imageView);
String[] url_array = getResources().getStringArray(R.array.url_images);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, url_array);
url_Spinner.setAdapter(adapter);
url_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String image_url = (String)url_Spinner.getItemAtPosition(position);
Picasso.with(getApplicationContext()).load(image_url).into(url_image_ImageView);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
activity_spinner_test_two.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:id="#+id/SpinnerTestTwoActivity_url_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp" />
<Button
android:id="#+id/SpinnerTestTwoActivity_load_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Load Image"
android:textAllCaps="false" />
<ImageView
android:id="#+id/SpinnerTestTwoActivity_image_from_url_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:layout_weight="1"
android:scaleType="fitCenter" />
</LinearLayout>
url_images
This is the array which you will make in the arrays.xml file which is in the res/values directory
<array name="url_images">
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7emgtQk5rdEE3bW8/style_icons_system_intro_principles_simple.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MGhHV055eGk0R2M/style_icons_system_intro_principles_intuitive.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MG80dmpHT0RidGs/style_icons_system_intro_principles_actionable.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7blViQzF0azNqZU0/style_icons_system_intro_principles_consistent.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7VXlvR05VSWhPZTg/style_icons_system_grid_geometry2.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7SUV1b2Z3b3NBazA/style_icons_system_best_do1.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7azQ4WThPb25NOGc/style_icons_system_best_do3.png</item>
</array>
Output
I have created a "InterestLine" class with a "lineContent" layout that has a TextView and a RatingBar.
Then I have created an adapter to make a listView of InterestLines on the main layout, so the user can see a list of text views + rating bar besides it, and rate every one of the elements.
public class MainActivity extends ActionBarActivity implements RatingBar.OnRatingBarChangeListener{
private String gender,age,output;
private List<InterestLine> lines;
private Button doneBtn;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] interest_list = {"//the list of text views//"};
lv=(ListView)findViewById(R.id.list_view);
lines=new ArrayList<InterestLine>();
for(String il:interest_list)
lines.add(new InterestLine(il));
ArrayAdapter<InterestLine> adapter=new ArrayAdapter<InterestLine>(this, R.layout.linecontent, R.id.tv1, lines);
lv.setAdapter(adapter);
doneBtn=(Button)findViewById(R.id.button1);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// collect stars (interests)
for(InterestLine il : lines)
output = output + il.getInterestName() + ":" + il.getNumberOfStars() + ",";
Log.i("OUTPUT", output);
}
});
}
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
// TODO Auto-generated method stub
}
I want to onClick of the button to collect all the ratings that were introduced by the user on the RatingBars, tried several methods without success.
Hope you can help me with this.
Thanks
The layout of the main activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list_view"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.86" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/done_btn"
android:layout_gravity="right" />
</LinearLayout>
And the layout of the line:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView
android:text="#string/line_text"
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:width="120sp" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_gravity="center_vertical" />
</LinearLayout>
It took me a while to figure it out. For this kind of complex layout, you should not use ArrayAdapter. You should make a custom adapter extend from BaseAdapter.
Here's the working Custom Adapter and Activity codes.
RatingAdapter
public class RatingAdapter extends BaseAdapter{
List<InterestLine> mInterestLineArrayList;
private RatingListener ratingListener;
public RatingAdapter(List<InterestLine> interestLines) {
mInterestLineArrayList = interestLines;
}
#Override public int getCount() {
return mInterestLineArrayList.size();
}
#Override public InterestLine getItem(int i) {
return mInterestLineArrayList.get(i);
}
#Override public long getItemId(int i) {
return i;
}
#Override public View getView(int i, View view, ViewGroup viewGroup) {
RatingViewHolder ratingViewHolder;
if(view==null){
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.linecontent,viewGroup,false);
ratingViewHolder = new RatingViewHolder(view);
view.setTag(ratingViewHolder);
}else{
ratingViewHolder = (RatingViewHolder) view.getTag();
}
ratingViewHolder.titleView.setText(getItem(i).getInterestName());
ratingViewHolder.ratingBar.setNumStars(getItem(i).getNumberOfStars());
ratingViewHolder.currentPosition = i;
return view;
}
public void setOnItemRatingChangeListener(RatingListener ratingListener){
this.ratingListener = ratingListener;
}
public interface RatingListener{
void onRatingBarClicked(RatingBar ratingBar, float v, boolean b,int position);
}
class RatingViewHolder implements RatingBar.OnRatingBarChangeListener{
private TextView titleView;
private RatingBar ratingBar;
private int currentPosition;
public RatingViewHolder(View view){
titleView = (TextView) view.findViewById(R.id.tv1);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar1);
ratingBar.setOnRatingBarChangeListener(this);
}
#Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
if(ratingListener!=null){
ratingListener.onRatingBarClicked(ratingBar,v,b,currentPosition);
}
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity{
private String gender, age, output;
private List<InterestLine> lines;
private Button doneBtn;
private ListView lv;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] interest_list = { "Hope","it's","ok" };
lv = (ListView) findViewById(R.id.list_view);
lines = new ArrayList<>();
for (String il : interest_list) {
InterestLine interestLine = new InterestLine();
interestLine.setInterestName(il);
lines.add(interestLine);
}
RatingAdapter adapter = new RatingAdapter(lines);
lv.setAdapter(adapter);
adapter.setOnItemRatingChangeListener(new RatingAdapter.RatingListener() {
#Override public void onRatingBarClicked(RatingBar ratingBar, float v, boolean b,int position) {
lines.get(position).setNumberOfStars((int)v);
}
});
doneBtn = (Button) findViewById(R.id.button1);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// collect stars (interests)
output = "";
for (InterestLine il : lines) {
output = il.getInterestName() + " " + il.getNumberOfStars();
Log.i("OUTPUT", output);
}
}
});
}
}
Basically, you create a custom adapter where you can get the instance of each rating bar. Then you set the OnRatingChangeListener on that rating bars. Then you get the desired rating value from the activity with the help of a callback. The tricky part here is getting the item position from the adapter. I solved this by storing the current item position in viewholder. Anyway, I would also like to point out that it will be a lot easier to use recycler view for this kind of thing.
I have a spinner within alert dialog. I wanted to reduce padding between spinner items and hence I implemented following:
spinner_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#fff" >
<TextView
android:id="#+id/tvCust"
android:layout_width="200dp"
android:layout_height="30dp"
android:gravity="left|center_vertical"
android:textColor="#000"
android:textSize="15sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
Activity code contains following:
spinner= (Spinner) dialog.findViewById(R.id.spinner);
String arr[] = { "1", "2", "3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
CameraActivity.this, R.layout.spinner_row, R.id.tvCust,arr);
spinner.setAdapter(adapter);
Now as you can see in below screenshot, radio button is getting displayed on spinner which is actually a part of spinner_row.xml. Note that textview width is 200dp while spinner is only 130dp long, so that radio button should not have been displayed on spinner. How can I remove it?
Also, when I click any of the spinner item, spinner pop-up doesn't get disappeared as expected.(note all 3 check-boxes are checked in spinner items list). setOnItemSelectedListener is not getting called on item click.
Any help appreciated.
Edit 1
As per farrukh's suggestion, I tried his code and following is the result.
I have this
and this
with these code of xml
xml for adapter named spinadapt.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#fff" >
<TextView
android:id="#+id/tvCust"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toLeftOf="#+id/radioButton1"
android:gravity="left|center_vertical"
android:textColor="#000"
android:textSize="15sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
and main layout named activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="Select item"
android:background="#drawable/spin"/>
</RelativeLayout>
and java code is class named MainActivity.java
public class MainActivity extends Activity
{
Spinner sp;
TextView tv;
String[] counting={"One","Two","Three","Four"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=new Spinner(this);
tv=(TextView)findViewById(R.id.spinner1);
tv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
sp.performClick();
}
});
sp.setAdapter(new Adapter(MainActivity.this, counting));
sp.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
tv.setText(counting[arg2]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
}
and adapter class named Adapter.java
public class Adapter extends BaseAdapter
{
LayoutInflater inflator;
String[] mCounting;
public Adapter( Context context ,String[] counting)
{
inflator = LayoutInflater.from(context);
mCounting=counting;
}
#Override
public int getCount()
{
return mCounting.length;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = inflator.inflate(R.layout.spinadapt, null);
TextView tv = (TextView) convertView.findViewById(R.id.tvCust);
tv.setText(Integer.toString(position));
return convertView;
}
}
this is working perfect
hope this will help
I'm trying to create an activity, RateCardActivity, which has a spinner in it. My layout file for RateCardActivity is rate_card. My RateCardActivity looks like the following.
public class RateCardActivity {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.rate_card);
Spinner spinner = (Spinner) findViewById(R.id.select_city);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.select_city, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
The layout file rate_card is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.olacabs.customer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:gravity="center"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:text="#string/rate_card"
android:textColor="#color/white"
android:textSize="20dp"
custom:customFont="litera_bold.ttf" />
<Spinner
android:id="#+id/select_city"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The RateCardActivity is called from another activity using an intent (I'm sure there is nothing wrong with that part of the code as when I substitute RateCardActivity with another activity, the application works fine). When I try to open the RateCardActivity in the application in emulator, the application crashes and I got the message "The application has stopped unexpectedly. Please try again later."
I can't seem to understand what I'm doing wrong, and want to know how to correct this?
Improve :public class RateCardActivity extends Activity
and add RateCardActivity to AndroidManifiest.xml
Hi you can use spinner activity by this way, I gave a sample code for the help..
public class MyActivity extends Activity {
public static EditText edtsample;
public static EditText edtchannel;
public static EditText edtencoding;
private static Spinner samplespin;
private static Spinner channelspin;
private static Spinner encodingspin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
edtsample = (EditText)findViewById(R.id.audvalue1);
edtchannel = (EditText)findViewById(R.id.chanvalue1);
edtencoding = (EditText)findViewById(R.id.encodingvalue1);
edtchannel.setFocusable(false);
edtchannel.setClickable(false);
edtencoding.setFocusable(false);
edtencoding.setClickable(false)
samplespin = (Spinner) findViewById(R.id.audspinner1);
samplespin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
edtsample.setText(parent.getItemAtPosition(position).toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
edtsample.setText("");
}
});
channelspin = (Spinner) findViewById(R.id.chanspinner1);
channelspin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if(parent.getItemAtPosition(position).equals("CHANNEL_PHONE")){
edtchannel.setText(R.string.chan1);
System.out.println("VALUE OF " +
edtchannel.getEditableText().toString()) ;
}
if(parent.getItemAtPosition(position).equals("CHANNEL_CD")){
edtchannel.setText(R.string.chan2);
System.out.println("VALUE OF " +
edtchannel.getEditableText().toString()) ;
}
if(parent.getItemAtPosition(position).equals("CHANNEL_HD")){
edtchannel.setText(R.string.chan2);
System.out.println("VALUE OF " +
edtchannel.getEditableText().toString()) ;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
edtchannel.setText("");
}
});
**And in XML part you do by this**
<Spinner
android:id="#+id/audspinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/audioText1"
android:spinnerMode= "dropdown"
android:entries="#array/sample_array" />
<EditText
android:id="#+id/audvalue1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/audspinner1"
android:hint="Enter Sampling Rate"
android:ems="10" >