trying to implement listview inside onclick function - android

public class CompanySearchActivity extends RathbonesActivity {
private CompanySearchAdapter mStockListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companysearch_layout);
final EditText keywordET = (EditText)findViewById(R.id.codeET);
final Button search = (Button)findViewById(R.id.button_stock_add);
final Activity a= CompanySearchActivity.this;
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this);
}
});
}
The lines listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this); are giving errors because of this keyword, i replaced it with 'a' too but it doesnt work. What can be the possible way to achieve this?

If you wish to use the parent activities onClick method your activity must implement OnItemClickListener and OnItemLongClickListener
public class CompanySearchActivity extends RathbonesActivity implements OnItemClickListener, OnItemLongClickListener
{
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
}
}
Note the code "implements OnItemClickListener, OnItemLongClickListener"
This is vital for implementing it this way.
Then you can call:
listview.setOnItemClickListener(CompanySearchActivity.this);
listview.setOnItemLongClickListener(CompanySearchActivity.this);

The this keyword is a reference to the object that owns the currently executing method. In this case this refers to the anonymous View.OnClickListener object that you are defining. Try replacing this with CompanySearchActivity.this

your listview onClick definition should look like your search listener.
search.setOnClickListener(new View.OnClickListener() {
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
}
});
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
<do somthing when its clicked>
}
});
also ensure if you have multiple layouts that these view items (listview and search)
are in companysearch_layout.xml

Related

prevent extra click on customdialogbox

I have one customdialog box which will appear on clicking the row of listview.And the data will display on customdialogbox from web service.Now ,if by mistake if i click twice, the customdialog box open twice.My custom dialog box is in Async class and i have call it on onPostexecute().
Every time i click on row of listview -it should called Async class in which customdialog box is there.
How to avoid to open it twice?
Please help.
I have checked some other condition but it is not working for me.
public void showCustomDialog() { // this is the dialog box i have created
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
final List<String> list=new ArrayList<String>();
list.add("Low");
list.add("Normal");
list.add("High");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialoguniversalappointment);
final ListView listcustomuniversalappt=(ListView) dialog.findViewById(R.id.listcustomuniversalappt);
LinearLayout layoutsubject=(LinearLayout) dialog.findViewById(R.id.layoutsubject);
LinearLayout layoutappt=(LinearLayout) dialog.findViewById(R.id.layoutappt);
Spinner spinnerappt=(Spinner)dialog.findViewById(R.id.permissionspinner);
ImageView cancel=(ImageView)dialog.findViewById(R.id.imgcancel);
Button cancelappt=(Button)dialog.findViewById(R.id.btncancelappt);
Button confirmappt=(Button)dialog.findViewById(R.id.btnconfirmappt);
EditText subject=(EditText) dialog.findViewById(R.id.edtsubject);
subject.setText("Appointment");
TextView txtdateslot=(TextView) dialog.findViewById(R.id.txtdateslot);
txtdateslot.setText("Date:"+DoctorAppointmentAPTrequest.universalapt_date+" Time Slot:"+DoctorAppointmentAPTrequest.universalslot_time);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerappt.setAdapter(dataAdapter);
spinnerappt.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
selected_item=arg0.getItemAtPosition(arg2).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
System.out.println("APTCustomRequestResponse.runcustomuniversalappdata="+run_custom_universal_apptdata());
APTRequestCustomAdapter adap=new APTRequestCustomAdapter(context,run_custom_universal_apptdata());
listcustomuniversalappt.setAdapter(adap);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
System.out.println("hello");
}
});
cancelappt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
//confirm appt
confirmappt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(APT_CustomRequestResponse.radiostring.equals("checked")){
showdialogforconfirmappointment();
}else{
Toast.makeText(context, "Please Select a Patient to book a Appointment",2000).show();
}
}
});
getsubject=subject.getText().toString();
if(!dialog.isShowing()||dialog==null){//here i am checking condition where it should appear or not
dialog.show();
System.out.println(isMatch);
}else{
dialog.dismiss();
}
}
and in onPost method i have called it:
public class APT_CustomRequestResponse extends AsyncTask<String,String,String>{
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
showCustomDialog();//here i am calling custom dialog box
#Override
protected String doInBackground(String... params) {
String hunt= GetAPT_RequestCustomdata();
return hunt;
}
}
}
This async class i am calling in other class where my actual listview is :
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
APT_CustomRequestResponse APT=new APT_CustomRequestResponse(MainActivity.this);
APT.execute();
Use below provided code for reference toward solving this issue.
// Keep this as member variable to the class
final Dialog dialog = new Dialog(context);
// your new method model
public void showCustomDialog() {
// Here check this
if(dialog != null && dialog.isShowing()){
// Decide if you want to display a new one, if yes then write below code first
dialog.dismiss();
dialog = null;
// Display a new dialog code here
}else{
// Dialog is no visible, diaply it here
}
}
Instead of try to avoid twice call of showCustomDialog() method try to avoid start AsyncTask again if task is already running on ListView row click. you can do this using AsyncTask.Status :
public boolean isfirsttimeclick=true;
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
APT_CustomRequestResponse APT=new APT_CustomRequestResponse(MainActivity.this);
if(isfirsttimeclick || APT.getStatus() == AsyncTask.Status.FINISHED){
APT.execute();
}else{
/// show message to user already running
}
}
You should not send a request to the server when item is clicked twice.
Either show a progress dialog in between while first request is sent that will prevent user from clicking at the list item again.
OR check in onItem click like #ρяσѕρєя K said just to add to that use following code define APT_CustomRequestResponse object outside of onItemClick and in your activity:
In activity:
APT_CustomRequestResponse APT=null;
onItemClick:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(MainActivity.this.APT==null||MainActivity.this.APT.getStatus() == AsyncTask.Status.FINISHED){
MainActivity.this.APT=new APT_CustomRequestResponse(MainActivity.this);
MainActivity.this.APT.execute();
}
}
EDIT
In you Async task create a boolean to know if execution is complete:
boolean finished=false;
And in post execute set it to true:
finished=true;
and finally do this in your onItemClick:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(MainActivity.this.APT==null||MainActivity.this.APT.finished){
MainActivity.this.APT=new APT_CustomRequestResponse(MainActivity.this);
MainActivity.this.APT.execute();
}
}

How can get ListView object in setOnClickListener?

In Code 2, I use final ListView lv=this.getListView() to get ListView object, it's OK.
In Code 1, I try to use ListView lv=((ListActivity)getApplicationContext()).getListView() to get ListView object, but it's bad.
Is there a simple way to get get ListView object in setOnClickListener? Thanks
Code 1
private void IniControl(){
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView lv=((ListActivity)getApplicationContext()).getListView();
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
Code 2
public class StepList extends ListActivity{
private ListNumberAdapter mListNumberAdapter=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_step_list);
}
private void IniControl(){
final ListView lv=this.getListView();
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Is IniControl also a method of StepList in your Code 1 ?
If so, you can simply call getListView() from there (the OnClickListener being an inner class of your StepList), or more explicitely StepList.this.getListView().
The ListView is not a member of the ApplicationContext. Why cant you add the ListView as a member of the Activity instead? Or use the getListView() on the ListActivity's context.
You can write separate OnClickListener method and pass ListView to it.
private View.OnClickListener onClick(final ListView lv) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
};
}
You can use onListItemClick Method
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "hoohoo..you clicked me at " + position,Toast.LENGTH_SHORT).show();
}
It will display the the row number you clicked
Make your ListView a class member Variable
private ListView mListView;
Then in onCreate(), call mListView = (ListView) this.getListView();
And then you can use the mListView object anywhere in the rest of the code.

setOnitemSelectedListener is not triggering with the programmatically created spinner Android

My need is to
create a dynamic spinner on a button click
select the spinner values and set the values into an edit text field.
For this I have created a dynamic spinner programatically. Put that code inside button click listener. Its working fine upto here.
but the setOnitemSelectedListener of the dynamic spinner is not at all working.. there are no errors in the Logcat... please help me..
------------ These are the methods inside onCreate ------------
Spinner spnOutHospitalList = new Spinner(Referance.this);
// list button on click event
btnList = (Button) findViewById(R.id.btn_list);
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// function to create spinner dynamically
createDynamicSpinner();
}
});
// Out Hospital List Spinner on item click listener
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
------------ These are the functions outside onCreate but inside the Activity------------
// to create spinner dynamically
private void createDynamicSpinner() {
// TODO Auto-generated method stub
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
loadOutHospitalListSpinner();
spnOutHospitalList.performClick();
}
// to load out hospital/ clinic data into spinner
private void loadOutHospitalListSpinner() {
// TODO Auto-generated method stub
try {
if (getFirstRun()) {
sampleDB = dbAdapter.getDatabase();
setRunned();
}
else {
sampleDB = dbAdapter.getWritableDatabase();
}
Cursor c1 = sampleDB.rawQuery("select DISTINCT EPR_OUT_HOSPITAL from EMR_PT_REFERNCE",null);
System.out.println("count is " + c1.getCount());
if (c1 != null && c1.getCount() != 0) {
hospitalNameListArray.clear();
if (c1.moveToFirst()) {
do {
hospitalNameListArray.add(c1.getString(c1.getColumnIndex("EPR_OUT_HOSPITAL")));
} while (c1.moveToNext());
}
}
c1.close();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, hospitalNameListArray);
// dropdownlist
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnOutHospitalList.setAdapter(dataAdapter);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("CAT LIST ERROR IS: " + e.getMessage());
}
}
Try this
Write setOnItemSelectedListener inside createDynamicSpinner
private void createDynamicSpinner() {
//Remove this line from top in your code and add here
Spinner spnOutHospitalList = new Spinner(Referance.this);
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//Pass Spinner Object to this function to load data in it!
loadOutHospitalListSpinner(spnOutHospitalList);
spnOutHospitalList.performClick();
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

How to handle an onClickListener for a Button within the Spinner onItemSelected(...) method?

I have a Spinner.onItemSelected() method and I want to be able to have an event happen once a Button is clicked after selecting the Spinner item.
For example if you select Beginner for your Spinner and click Java for another spinner. Under that I have a button that says Start. How do I have a Button.onClick event correspond with the selected spinner options?
I did something like this but what I assigned as the setOnClickListener() value is not being read by the View.OnClickListener.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selected = (Integer) arg0.getItemAtPosition(0);
position = spinner.getSelectedItemPosition();
start = (Button)findViewById(R.id.start);
start.setOnClickListener(phaseHandler);
View.OnClickListener phaseHandler = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
}
The phaseHandler I declared is not being read by start.setOnClickListener(phaseHandler) so this results in my View.OnCLickListenr invocation not working because phaseHandler is not being set to the Button start. In Eclipse my phaseHandler has the red underlining curly for an error where it says start.setOnClickListener(phaseHandler);
Any Ideas?
move start.setOnClickListener(phaseHandler); down
this may help you
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selected = (Integer) arg0.getItemAtPosition(0);
position = spinner.getSelectedItemPosition();
start = (Button)findViewById(R.id.start);
View.OnClickListener phaseHandler = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
start.setOnClickListener(phaseHandler);
}

Deleting last item from spinner deletes the entire list

I am trying to use a spinner control that will enable the user to delete any list element.
I have an 'add' button to add elements to the list, and a 'delete' button that removes the currently-displayed item from the list.
It works as expected except when the user deletes the last item in the list. At that point, all of the list's items are deleted.
My code is as follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// grab our UI elements so we can manipulate them (for the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
((ArrayAdapter)m_adapterForSpinner).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// add listener for addButton
private void addNewSpinnerItem() {
if (m_addItemText.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "The textView is empty", Toast.LENGTH_LONG).show();
} else {
CharSequence textHolder = "" + m_addItemText.getText();
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO
}
});
}
Does anyone have any ideas or suggestions on how to make this work?
The problem with your code is that the deletion is inside the onItemSelected callback, which gets called every time you are deleting an entry, thus deleting recursively until you effectively do not have any more entries to select. If you add a log inside that method:
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
you will see what I mean. I'm sure you can come up with more elegant code, but a quick and dirty hack is to set up a boolean flag to stop the recursion after the first deletion. See the snippet below and add the commented lines to your own code:
public class SpinnerTest extends Activity {
Spinner m_myDynamicSpinner;
EditText m_addItemText;
ArrayAdapter m_adapterForSpinner;
public static boolean cleared = false; // <--- set up a static boolean here
#Override
public void onCreate(Bundle savedInstanceState) {
// all your code unchanged
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cleared=false; // <--- nope, we did not clear the value yet
clearSpinnerItems();
}
});
}
// code unchanged
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
if (!cleared) // <--- did I do it already?
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
cleared=true; // I did it!
}
// code unchanged
i cann't understand your question.any way you can get the position of the selected item by using getSelectedItemPosition() method.

Categories

Resources