hi all Am having listview which displays list of items from sqlite db. Using DialogBox am inserting data in DB. Insertion done successfully. But if i entered data on DialogBox and click ok button, the data inserted in db but the inserted data is not displaying in ListView.
ListView is not refreshing.... I hv used adapter.setNotifyOnChange(true);. But this wont take any effect on listview.
And I have got warning on logcat as
`09-16 15:01:10.215: INFO/dalvikvm(2066): Uncaught exception thrown by finalizer (will be discarded):
09-16 15:01:10.215: INFO/dalvikvm(2066): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor#44c4be28 on PAYMENT_TABLE that has not been deactivated or closed
09-16 15:01:10.215: INFO/dalvikvm(2066): at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596)
09-16 15:01:10.215: INFO/dalvikvm(2066): at dalvik.system.NativeStart.run(Native Method)`
But i hv closed the cursor in OnDestory()
Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
String mTitleRaw = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_PAYMENT_TYPE));
al.add(mTitleRaw);
cursor.moveToNext();
}
adapterChanged();
}
#SuppressWarnings("unchecked")
private void adapterChanged() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, al);
adapter.setNotifyOnChange(true);
setListAdapter(adapter);
listContent = getListView();
listContent.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
//Object o = this.getListAdapter().getItem(position);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mySQLiteAdapter != null) {
mySQLiteAdapter.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, MENU_ADD, 0, "Add New");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()) {
case MENU_ADD:
AlertMsg();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateList(){
cursor.requery();
}
public void AlertMsg() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Payment Type");
alert.setMessage("Add field");
final EditText mTxt = new EditText(this);
alert.setView(mTxt);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String mNewField = mTxt.getText().toString();
//Toast.makeText(getApplicationContext(), "Item " + mNewField + " Added", Toast.LENGTH_LONG).show();
mySQLiteAdapter.insert(mNewField);
updateList();
adapterChanged();
}
});
alert.show();
}
}
Are this efficient way....
Can anyone pls give some suggestions.....
Thanks......
Related
i try using SQLite in Fragment. But always error. I know that my syntax isn't great and I should be saving from a Party object instead of straight from the fragment interface, but my focus is really on the the process. Any help would be super helpful! Here my code. I try using getActivity() but not work.
public class DataHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "biodatadiri.db";
private static final int DATABASE_VERSION = 1;
public DataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table biodata(no integer primary key, nama text null, tgl text null, jk text null, alamat text null);";
Log.d("Data", "onCreate: " + sql);
db.execSQL(sql);
sql = "INSERT INTO biodata (no, nama, tgl, jk, alamat) VALUES ('1001', 'Fathur', '1994-02-03', 'Laki-laki','Jakarta');";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
And here is the interface screen:
public class UserFragment extends Fragment {
String[] daftar;
ListView ListView01;
Menu menu;
protected Cursor cursor;
DataHelper dbcenter;
public static UserFragment ma;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_fragment);
Button btn=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(UserFragment.this, BuatBiodata.class);
startActivity(inte);
}
});
ma = this;
dbcenter = new DataHelper(this);
RefreshList();
}
public void RefreshList(){
SQLiteDatabase db = dbcenter.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM biodata",null);
daftar = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++){
cursor.moveToPosition(cc);
daftar[cc] = cursor.getString(1).toString();
}
ListView01 = (ListView)findViewById(R.id.listView1);
ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftar));
ListView01.setSelected(true);
ListView01.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
final String selection = daftar[arg2]; //.getItemAtPosition(arg2).toString();
final CharSequence[] dialogitem = {"Lihat Biodata", "Update Biodata", "Hapus Biodata"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserFragment.this);
builder.setTitle("Pilihan");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), LihatBiodata.class);
i.putExtra("nama", selection);
startActivity(i);
break;
case 1 :
Intent in = new Intent(getApplicationContext(), UpdateBiodata.class);
in.putExtra("nama", selection);
startActivity(in);
break;
case 2 :
SQLiteDatabase db = dbcenter.getWritableDatabase();
db.execSQL("delete from biodata where nama = '"+selection+"'");
RefreshList();
break;
}
}
});
builder.create().show();
}});
((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Here is error from Android Studio.
Error:(81, 25) error: method updateDisplay in class MainMenu cannot be applied to given types;
required: Fragment
found: UserFragment
reason: actual argument UserFragment cannot be converted to Fragment by method invocation conversion
I use case in MainMenu.java
case R.id.navigation_item_user:
updateDisplay(new UserFragment());
break;
Anyone? Thank you for your help :) Sorry for bad english
setContentView(R.layout.user_fragment); // this call should be made only activity.
In Fragments you need to override onCreateView method to setup view. In this return the view that you show it in fragment
Best explained here
fragments with transactions
usage
//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView
this is my code, If add the if statement in line No 105 then program crashes, if i removed this then my code is working. But without this i can't solve my code. Please can anyone tell me what could be the problem or what am i doing wrong?
public class SMSDetails extends Activity {
Spinner examSpinnerSMS,yearSpinnerSMS,boardSpinnerSMS;
private String[] examinationStrings;
private String[] yearStrings;
private String[] boardStrings;
int index;
private String mSelectedItemExam,mSelectedItemYear,mSelectedItemBoard;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsdetails);
//initialize view
examSpinnerSMS = (Spinner)findViewById(R.id.spnrExamination);
yearSpinnerSMS=(Spinner)findViewById(R.id.spnrYear);
boardSpinnerSMS=(Spinner)findViewById(R.id.spnrBoard);
//initialize data source
examinationStrings = getResources().getStringArray(R.array.Examination);
yearStrings = getResources().getStringArray(R.array.YearArray);
boardStrings = getResources().getStringArray(R.array.Board);
//initialize view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, examinationStrings);
ArrayAdapter<String> adapter1= new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, yearStrings);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, boardStrings);
//bind adapter and view
examSpinnerSMS.setAdapter(adapter);
yearSpinnerSMS.setAdapter(adapter1);
boardSpinnerSMS.setAdapter(adapter2);
//work with the spinners
examSpinnerSMS.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,int arg2, long arg3) {
//index = examSpinnerSMS.getSelectedItemPosition();
mSelectedItemExam=arg0.getSelectedItem().toString();
//Toast.makeText(getApplicationContext(),"You have selected "+mSelectedItemExam,Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
yearSpinnerSMS.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,int arg2, long arg3) {
//index = examSpinnerSMS.getSelectedItemPosition();
mSelectedItemYear=arg0.getSelectedItem().toString();
//Toast.makeText(getApplicationContext(),"You have selected "+mSelectedItemYear,Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
boardSpinnerSMS.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,int arg2, long arg3) {
index = examSpinnerSMS.getSelectedItemPosition();
mSelectedItemBoard=arg0.getSelectedItem().toString();
//Toast.makeText(getApplicationContext(),"You have selected "+mSelectedItemBoard,Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
//Log.i("problem", "problem");
//problem is here
if (mSelectedItemExam.equals("Select One")||mSelectedItemYear.equals("Select One")|| mSelectedItemBoard.equals("Select One")) {
Toast.makeText(getApplicationContext(), "Enter all the value", Toast.LENGTH_SHORT).show();
}
//Log.i("problem", "problem");
}
public void Submit(View view) {
String fm = mSelectedItemExam+" "+mSelectedItemBoard+" "+mSelectedItemYear;
//Log.i("problem", "problem");
try {
sendSMS("5556", fm);
Toast.makeText(getApplicationContext(), "SMS sent",
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.smsdetails, menu);
return true;
}
}
do you mean that you need to add an if statement in this lines?:
catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Please add the statement where it is not compiling.
mSelectedItemExam is probably null because none has been selected at the time you're doing
mSelectedItemExam.equals("Select One")
Learn how to use the Logcat and next time post a stracktrace :)
In my application i am using 2 spinners.I am using onitemselectedListener on both spinners but in my second spinner listener is not working.
if someone can suggest me proper solution....
my code is....
public class Expense extends Activity {
Spinner datype,distance;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.expense);
datype=(Spinner)findViewById(R.id.da_type);
distance=(Spinner)findViewById(R.id.da_distance);
List<String>data1=new ArrayList<String>();
data1.add("Local");
data1.add("Ex-Station Double Side");
data1.add("Ex-Station Single Side");
data1.add("Out-Station Double Side");
data1.add("Out-Station Single Side");
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,data1);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
datype.setAdapter(adapter);
datype.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(datype.getSelectedItem().toString().equals("Local")){
mainlayout.setVisibility(View.GONE);
}
else {
mainlayout.setVisibility(View.VISIBLE);
}
if(datype.getSelectedItem().toString().equals("Local")){
try{
Statement smt=mycon.connection().createStatement();
rs=smt.executeQuery("DCR_GETEXPENSE '"+PA_ID+"'");
while(rs.next()){
daAmt.setText(rs.getString("DA_L"));
}
}catch(Exception e){
e.printStackTrace();
}
}
else if(datype.getSelectedItem().toString().equals("Ex-Station Double Side")||datype.getSelectedItem().toString().equals("Ex-Station Single Side")){
try{
Statement smt=mycon.connection().createStatement();
rs=smt.executeQuery("DCR_GETEXPENSE '"+PA_ID+"'");
while(rs.next()){
daAmt.setText(rs.getString("DA_EX"));
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
try{
Statement smt=mycon.connection().createStatement();
rs=smt.executeQuery("DCR_GETEXPENSE '"+PA_ID+"'");
while(rs.next()){
daAmt.setText(rs.getString("DA_NS"));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
station=new ArrayList<String>();
try{
CallableStatement stmt=mycon.connection().prepareCall("DCRDOCTORGRID '"+PA_ID+"','','','','','','',''");
stmt.execute();
rs=stmt.getResultSet();
rs.close();//i'st table
stmt.getMoreResults();
rs=stmt.getResultSet();
rs.close();//2'nd table
stmt.getMoreResults();
rs=stmt.getResultSet();
while(rs.next()){
station.add(rs.getString("STATION_NAME"));
}
}catch(Exception e){
e.printStackTrace();
}
ArrayAdapter<String>adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,station);
adapter2.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
distance.setAdapter(adapter2);
distance.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(distance.getSelectedItem().toString().equals("Zero Kilometer")){
Toast.makeText(getApplicationContext(),"0000",Toast.LENGTH.Short).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
In second spinner my toast is not displaying when i select that value from spinner
please help me
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
}
});
}