I am trying to use the searchable spinner library but it is not working, here is the code. The spinner works well, But I would really like the search feature too from the library
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityHome);
SearchableSpinner spinner = (SearchableSpinner) findViewById(R.id.spinner);
initControls();
}
private void initControls(){
SearchableSpinner spinner = (SearchableSpinner) findViewById(R.id.spinner);
spinner.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isSpinnerTouched){
selectedItem = adapterView.getItemAtPosition(i).toString();
code = getCode(selectedItem);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
proceed_button_new = (TextView) findViewById(R.id.proceed_button_new);
proceed_button_new.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
}
});
List<Food> data = getData();
List<String> foodNames = getFoodNamesFromData(data);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, foodNames);
spinner.setAdapter(adapter);
}
Related
Based on information from Android: Create spinner programmatically from array. I can select room choices from spinner based on ArrayList. However,it never get inside the process setOnItemSelectedListener.I cannot figure out why does it happen.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_room);
SpaceRoomTable = (TableLayout) findViewById(R.id.tvSpaceRoomTable);
AddroomButton = (Button)findViewById(R.id.btLinkAddRoom);
Backtomenu = (Button) findViewById(R.id.bBackToMenu_DogTrack);
Delete = ContextCompat.getDrawable(this, R.drawable.bin);
dropdown = (Spinner) findViewById(R.id.spinListRoom);
summitDelete = (Button) findViewById(R.id.btDeleteSummit);
AddroomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToEditroom = new Intent (EditRoom.this,AddRoom.class);
startActivity(LinkToEditroom);
}
});
Backtomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LinkToHomeMenu = new Intent(EditRoom.this,HomeMenu.class);
EditRoom.this.startActivity(LinkToHomeMenu);
}
});
showRoom();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
Object Itemselected = adapterView.getItemAtPosition(i);
Toast.makeText(getApplicationContext(),"Inside"+String.valueOf(Itemselected),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
In XML Layout :-
<Spinner
android:id="#+id/dropdown"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
then, in your activity findViewById like this:-
dropdown= (Spinner) findViewById(R.id.dropdown);
then Create an ArrayAdapter using the string array and a default spinner layout :-
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
For OnIemClickListener use like this:-
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner dropdown;
String[] showitemName = {"A","B","C","D","E"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown= (Spinner) findViewById(R.id.dropdown);
dropdown.setOnItemSelectedListener(this);
ArrayAdapter<String> spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,showitemName);
spinnerArrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(spinnerArrayAdapter);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),"Inside" + parent.getItemAtPosition(position) , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
More information:
You can check in details from these links:-
https://developer.android.com/guide/topics/ui/controls/spinner.html
https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
https://android--code.blogspot.in/2015/08/android-spinner-onitemselected.html
http://www.java2s.com/Code/Android/UI/SpinnerItemSelectedListener.htm
https://android--code.blogspot.in/2015/08/android-spinner-get-selected-item-text.html
For more Information about showroom method
public void showRoom()
{
refroom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
int Length_Record = dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").child("LIST_ROOM_LENGTH").getValue(int.class);
int RunRecord =0;
int printRoom =0;
final String userId = dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class);
for (DataSnapshot zonesnapshot : dataSnapshot.child("CurrentUser").child("Tracking").child("ListRoom").getChildren())
{
if(printRoom!=Length_Record)
{
zonesnapshot.getValue();
String[] parts = String.valueOf(zonesnapshot.getValue()).split(",");
String part1 = parts[0]; // Room Id
String part2 = parts[1]; // Room Name
String part3 = parts[2]; // TypeRoom
String OnRoom = dataSnapshot.child("CurrentUser").child("Tracking").child("Location").getValue(String.class);
itemsName.add(part2+","+part3); // put to arraylist to prepare a room choice for deletion
showitemName.add(part2+"("+part3+")");
itemOfUser.put(userId+"Room"+printRoom,part2+","+part3); // keep room for each user
inRow(dataSnapshot.child("CurrentUser").child("UserId").getValue(String.class), RunRecord, part2, OnRoom, part3);
}
printRoom++;
}
summitDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storageReference = storage.getInstance().getReferenceFromUrl("gs://********-*****.appspot.com/imagesRoom").child(userId).child(selection);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error Can not delete file",Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
below code will get the selected item text automatically
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Log.d("TEST","selection is ");
String item = adapterView.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),"Inside"+item,Toast.LENGTH_SHORT).show();
}
I am filtering my data using onQueryTextChange, the list filters but it still shows the old data set(unfiltered) which results in data from the old list, even though it shows the new filtered list.
Can someone fix my code which will display the right data set after filter, and unfiltered dataset when the a user will clear the search text.
I will explain it better with screenshots.
Before filter Screenshot 1, clicking on a item will toast the text on it.
After Filter Screenshot 2, on click it is supposed to say HDFC BANK, instead it still shows the data from Position 1 from the unfiltered data set.
I was told its because I am using the BankNames List (unfiltered) text at position when clicking, because of which this is happening.
Can someone please fix my logic here, I am unable to figure this out, even though it seems simple, I am new to Android.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
final List<DataAdapter> filteredModelList = new ArrayList<>();
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Make global variable for filteredList and take data from that list. The error happened because you are toasting from the full list. Not filteredList
Try this
may this issue that your are Printing Toast of BankNames.get(RecyclerViewClickedItemPOS) from your Oldlist not From the filteredModelList
Remove this
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
and set Toast in Adapter class
viewHolder.TextViewName..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, dataAdapter.getBankName(), Toast.LENGTH_SHORT).show();
}
});
Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last
I have a problem in my codes in AutocompleteTextView. When I search , after I click the word that I have search it will display some text or letters in AutocompleteTextView .
This is my the main page of the app Main of the app
After I search the word . It will display this This is the error image
This is my code :
MainActivity.java
public class MainActivity extends Activity {
Button AN,PL;
AutoCompleteTextView autocomplete;
Button clear;
ListView lv;
SearchView search_view;
String[] animals_names;
ArrayList<Main> animalslist;
AnimalsAdapter adapter;
#SuppressWarnings("rawtypes")
Class[] classes = {
A.class,
B.class,
C.class,
D.class,
E.class,
F.class,
G.class,
H.class,
I.class,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_activity_main);
AN= (Button) findViewById(R.id.button1);
PL= (Button) findViewById(R.id.button2);
lv = (ListView) findViewById(R.id.list_view);
autocomplete = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
clear = (Button) findViewById(R.id.clear);
clear.setVisibility(View.INVISIBLE);
animals_names = getResources().getStringArray(R.array.animals_names);
animalslist = new ArrayList<Main>();
for (int i = 0; i < animals_names.length; i++) {
Main country = new Main(i,animals_names[i], classes[i]);
animalslist.add(country);
}
adapter = new AnimalsAdapter(getApplicationContext(), animalslist);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, animals_names);
autocomplete.setAdapter(this.adapter);
autocomplete.setThreshold(1);
autocomplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Main item = (Main) parent.getAdapter().getItem(position);
Intent d = new Intent(MainActivity.this, item.getClazz());
startActivity(d);
/** Fading Transition Effect */
MainActivity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
autocomplete.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
//do nothing
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length() != 0) {
clear.setVisibility(View.VISIBLE);
} else {
clear.setVisibility(View.GONE);
}
}
});
autocomplete.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
clear.setVisibility(View.VISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
clear.setVisibility(View.GONE);
}
});
}
public void clear(View view) {
autocomplete.setText("");
clear.setVisibility(View.GONE);
}
I want to take the value in spinner and user press the ok Button and then start new activity from against the value of spinner. The string array is just like that. and I use two spinners value get and new activity start against the spinners
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
//#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
s1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
// #Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}
here is the code this can error generate. Sorry application has been stopped
so i stuck on this code.
use setOnItemSelectedListener instead of setOnItemClickListener:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Spinner s, s1;
Button ok;
Object _globalString, _globalString2;
String[] array_spinner = {"Honda", "Toyota"};
String[] array_spinner01 = {"Civic", "Gli"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
s1.setAdapter(adapter1);
//
// s2=(Spinner)findViewById(R.id.spinner02);
// ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
// s2.setAdapter(adapter2);
ok = (Button) findViewById(R.id.btn_ok);
ok.setOnClickListener(this);
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
_globalString2 = parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_ok) {
if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
startActivity(new Intent(getApplicationContext(), Civic.class));
} else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
startActivity(new Intent(getApplicationContext(), Toyota.class));
}
}
}
}