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 :)
Related
I am using viewPager in a Fragment. Viewpager contains 5
fragments named 1) General 2) ozone 3) Myzone 4) Bizzone 5) Password.
All the fragments are getting value from json and its working well.
First fragments (general) is dealing with 4 different api in which 3
are dedicated to three different spinners and 1 is to get the final
values for complete view.
Now the question is, I swap the views by viewPager and reach to last
fragment, when I come to the first view, it loses the value of Spinner
and they become empty.
This is the code which I am using to set the values in view.
public class ProfileGeneralSetting extends Fragment implements MiFeelingBase, OnClickListener{
public Spinner spCountryName;
public Spinner spCityName;
public Spinner spTimeZone;
private RadioGroup rg1;
private RadioButton rbEnable, rbDisable;
public Button SettingSaveGeneral;
public EditText edGeneralFullname,edGeneralEmail,edGeneralFirstName,edGeneralLastName,edGeneralMobileNumber,edGeneralAddress1,
edGeneralAddress2,edtUser_Dob,edtEducationInstitude,edtDegree,edtGrade,edtStartYear,edtEndYear,edtStream;
public int mYear;
public int mMonth;
public int mDay;
ProgressDialog mProgressDialog;
ArrayList<Country> countryList = new ArrayList<Country>();
ArrayList<Country>cityList=new ArrayList<Country>();
ArrayList<Country>timeList=new ArrayList<Country>();
GeneralSettingData generalList = new GeneralSettingData();
private GeneralSettingAdapter adapter;
private GeneralSettingAdapter2 adapter2;
private GeneralSettingAdapter3 adapter3;
//private GeneralSettingAdapter4 adapter4;
Context context;
public ImageView Usercalender;
private static final int DATE_DIALOG_ID = 0;
private String strUserID;
private int index=0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.profilesettinggeneral, container, false);
rg1 = (RadioGroup)rootView.findViewById(R.id.rg1);
spCountryName = (Spinner)rootView.findViewById(R.id.spCountryName);
spCityName = (Spinner)rootView.findViewById(R.id.spCityName);
spTimeZone = (Spinner)rootView.findViewById(R.id.spTimeZone);
edGeneralFullname = (EditText)rootView.findViewById(R.id.edGeneralFullname);
edGeneralEmail = (EditText)rootView.findViewById(R.id.edGeneralEmail);
edGeneralFirstName = (EditText)rootView.findViewById(R.id.edGeneralFirstName);
edGeneralLastName = (EditText)rootView.findViewById(R.id.edGeneralLastName);
edGeneralMobileNumber = (EditText)rootView.findViewById(R.id.edGeneralMobileNumber);
edGeneralAddress1 = (EditText)rootView.findViewById(R.id.edGeneralAddress1);
edGeneralAddress2 = (EditText)rootView.findViewById(R.id.edGeneralAddress2);
edtUser_Dob = (EditText)rootView.findViewById(R.id.edtUser_Dob);
edtEducationInstitude = (EditText)rootView.findViewById(R.id.edtEducationInstitude);
edtDegree = (EditText)rootView.findViewById(R.id.edtDegree);
edtGrade = (EditText)rootView.findViewById(R.id.edtGrade);
edtStartYear = (EditText)rootView.findViewById(R.id.edtStartYear);
edtEndYear = (EditText)rootView.findViewById(R.id.edtEndYear);
edtStream = (EditText)rootView.findViewById(R.id.edtStream);
Usercalender = (ImageView)rootView.findViewById(R.id.Usercalender);
rbEnable = (RadioButton)rootView.findViewById(R.id.rbEnable);
rbDisable = (RadioButton)rootView.findViewById(R.id.rbDisable);
SettingSaveGeneral = (Button)rootView.findViewById(R.id.SettingSaveGeneral);
SettingSaveGeneral.setOnClickListener(this);
Usercalender.setOnClickListener(this);
rbEnable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "enabled", Toast.LENGTH_SHORT).show();
}
});
rbDisable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "disabled", Toast.LENGTH_SHORT).show();
}
});
/*rg1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(checkedId == R.id.rbEnable){
Toast.makeText(context, "enabled", Toast.LENGTH_SHORT).show();
}else if(checkedId == R.id.rbDisable){
Toast.makeText(context, "disabled", Toast.LENGTH_SHORT).show();
}
}
});*/
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
Usercalender.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener(){
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth){
edtUser_Dob.setText(year + "-"+ (monthOfYear + 1) + "-" + dayOfMonth);
}
}, mYear, mMonth, mDay);
dpd.show();
}
});
//spCountryName.("Counrty");
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
AppContoller.getInstance().pref=getActivity().getSharedPreferences(AppContoller.getInstance().PREF_NAME, 0);
strUserID=AppContoller.getInstance().pref.getString(AppContoller.getInstance().USER_ID, "0");
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
savedInstanceState
/*rg1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if(checkedId == R.id.rbEnable){
Toast.makeText(context, "enabled", Toast.LENGTH_SHORT).show();
}else if(checkedId == R.id.rbDisable){
Toast.makeText(context, "disabled", Toast.LENGTH_SHORT).show();
}
}
});*/
}
#Override
public String httpPost() {
// TODO Auto-generated method stub
String response="";
if(index==0)
{
response=OpenConnection.callUrl(StaticData.SABAKUCH_GENERAL_SETTING_COUNTRY);
}else if(index==1)
{
response=OpenConnection.callUrl(StaticData.SABAKUCH_GENERAL_SETTING_CITY);
}else if(index==2)
{
response=OpenConnection.callUrl(StaticData.SABAKUCH_GENERAL_SETTING_TIMEZONE);
}
else if(index==3)
{
response = OpenConnection.callUrl(StaticData.SABAKUCH_GENERAL_SETTING_GETDATA+strUserID);
}
//Log.d("RespoNCEEEEEEEEE", response);
return response;
}
#Override
public String httpAfterPost(String str) {
// TODO Auto-generated method stub
if(str!=null)
{
if(index==0){
countryList=SabaKuchParse.parseCountryData(str);
if(countryList.size()>0)
{
adapter=new GeneralSettingAdapter(getActivity(), countryList);
spCountryName.setAdapter(adapter);
index=1;
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
}
}else if(index==1)
{
cityList=SabaKuchParse.parseCityData(str);
if(cityList.size()>0)
{
adapter2=new GeneralSettingAdapter2(getActivity(), cityList);
spCityName.setAdapter(adapter2);
index=2;
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
}
}else if(index==2)
{
timeList = SabaKuchParse.parseTimeData(str);
if(timeList.size()>0){
adapter3 = new GeneralSettingAdapter3(getActivity(),timeList);
spTimeZone.setAdapter(adapter3);
index=3;
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
}
}
else if(index==3)
{
generalList = SabaKuchParse.parseFullData(str);
edGeneralFullname.setText(generalList.strFname);
edGeneralEmail.setText(generalList.strEmail);
String tt = generalList.strEmail;
Log.d("helloooooooooooooooooooo", tt);
edGeneralFirstName.setText(generalList.strFname);
edGeneralLastName.setText(generalList.strlname);
edGeneralMobileNumber.setText(generalList.strContact);
edGeneralAddress1.setText(generalList.strAddress1);
edGeneralAddress2.setText(generalList.strAddress2);
edtUser_Dob.setText(generalList.strDob);
edtEducationInstitude.setText(generalList.arr.get(0).strSchool);
edtDegree.setText(generalList.arr.get(0).strDegree);
edtGrade.setText(generalList.arr.get(0).strGrade);
edtStartYear.setText(generalList.arr.get(0).strFrom_date);
edtEndYear.setText(generalList.arr.get(0).strTo_date);
edtStream.setText(generalList.arr.get(0).strField_study);
String ss = generalList.strTime_zone;
Log.d("jhakkasss", ss);
for(int i=0;i<timeList.size();i++)
{
if( timeList.get(i).strTimezoneid.equalsIgnoreCase(generalList.strTime_zone))
{
spTimeZone.setSelection(i);
}
}
for(int i=0;i<countryList.size();i++)
{
if( countryList.get(i).strCountryid.equalsIgnoreCase(generalList.strCountry_id))
{
spCountryName.setSelection(i);
}
}
for(int i=0;i<cityList.size();i++)
{
if(cityList.get(i).strCityid.equalsIgnoreCase(generalList.strCity_id))
{
spCityName.setSelection(i);
}
}
}else if(index==5){
}
}
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.SettingSaveGeneral:
index =5;
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
break;
default:
break;
}
}
}
this is my Main fragment class where I have created viewPager
public class ProfileSettingFragment extends android.support.v4.app.Fragment implements TabListener {
private ViewPager mPager;
private MyPageAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.profile_setting_fragment, container, false);
mPager=(ViewPager)rootView.findViewById(R.id.pager);
mPager.setOffscreenPageLimit(2);
adapter=new MyPageAdapter(getChildFragmentManager());
mPager.setAdapter(adapter);
TabPageIndicator indicater=(TabPageIndicator)rootView.findViewById(R.id.indicator1);
indicater.setViewPager(mPager);
indicater.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
/*mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});*/
/*actionBar.addTab(actionBar.newTab().setText("Home").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("MiZone").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Top Trending").setTabListener(this));
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);*/
return rootView;
}
private class MyPageAdapter extends FragmentStatePagerAdapter
{
private List<android.support.v4.app.Fragment> fragments;
public MyPageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
this.fragments=new ArrayList<android.support.v4.app.Fragment>();
fragments.add(new ProfileGeneralSetting());
fragments.add(new ProfileOzoneSetting());
fragments.add(new ProfileMyzoneSetting());
fragments.add(new ProfileBizzoneSetting());
fragments.add(new ProfilePasswordSetting());
}
#Override
public android.support.v4.app.Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return fragments.get(arg0);
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0:
return "General";
case 1:
return "Ozone";
case 2:
return "MyZone";
case 3:
return "BizZone";
case 4 :
return "Password Setting";
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragments.size();
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
It's strange that although you are using mPager.setOffscreenPageLimit(2); your fragments are still recreated. Are you sure there isn't a data loading problem in your fragments?
I have solved my problem. I added this code of line to my fragment.
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroyView();
index =0;
APIAccess.fetchData(ProfileGeneralSetting.this, getActivity(), getActivity());
}
and also change this mPager.setOffscreenPageLimit(2); into this mPager.setOffscreenPageLimit(2);
Now its working properly as I want.
Thanks every one for your kind help.:)
When a fragment is no longer displayed, it may be shut down by the system.
You can save their state using OnSaveInstanceState or make use of call setRetainInstance(true) in your fragment OnCreate
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle)
You didn't post the code for your fragments, but I bet you are not saving their state.
In your httpAfterPost() method, it looks like you are creating the spinner adapter then sending it to the fragment. In the fragment, you need to access the list data that the adapter has and save it by overriding onSaveInstanceState(), then bringing the data back in onCreate() from the savedInstanceState bundle.
It might be better to pass the data to the fragment and let it create the adapter, rather than creating the adapter first and handing it to the fragment. Either way, you have to get at that list data and save/restore it.
In order to be saved, your Country class needs to implement either Serializable or Parcelable, which is Android DIY serialization.
Override onSavedInstanceState()
#Override
public void onSavedInstanceState(Bundle outstate) {
outState.putSerializable("countryList", (Serializable) countryList); // if Country implements Serializable
// or
outState.putParcelable("countryList", (Parcelable) countryList);
super.onSavedInstanceState(outState);
}
In onCreate(), add this line:
countryList = (ArrayList<Country>) savedInstanceState.getSerializable("countryList");
or
countryList = (ArrayList<Country>) savedInstanceState.getParcelableArrayList("countryList");
Also recreate your spinner adapters here once you have your list back.
Repeat this for all the spinner adapter lists that are disappearing.
I have a program in android where spinner gets the data dynamically from rest services. what i want to achieve is when the first spinner loads its value, the selected value loads the value of 2nd and third spinner. i want to disable the click of 2nd and third spinner till the spinner gets populated are loaded in all the spinner.
I call the function of populating 2nd & 3rd spinner in the end of the program.
public void addItemsOnSpinner1()
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null) {
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
JSONObject login = new JSONObject();
try
{
login.put("EmployeeID",strEmployeeID);
//login.put("Password", etCountry.getText().toString());
JSONObject finaldata = new JSONObject();
finaldata.put("ProjectRequest", login);
final ConnectToServer connect = new ConnectToServer();
connect.extConnectToServer(HourlyEntry.this,new ConnectToServer.Callback()
{
public void callFinished(String result)
{
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject resp = null;
try
{
resp = new JSONObject(result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject Login1Result = resp.getJSONObject("ProjectResult");
JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
// String strMessage = Login1Result.getString("message");
// Toast.makeText(getBaseContext(), Login1Result.getString("ProjectDetails"), Toast.LENGTH_LONG).show();
// List<String> list = new ArrayList<String>();
if (!Login1Result.getString("ProjectDetails").equalsIgnoreCase("null"))
{
//JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
m_Project_list = new ArrayList<String>();
m_projectID_list = new ArrayList<String>();
for (int i = 0; i < DepartmentDetails.length(); i++)
{
JSONObject m_DepartmentDetails = DepartmentDetails.getJSONObject(i);
// Toast.makeText(getBaseContext(),m_DepartmentDetails.toString() , Toast.LENGTH_LONG).show();
if (!m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase(""))
{
// list.add(m_DepartmentDetails.getString("ProjectName"));
m_Project_list.add(m_DepartmentDetails.getString("ProjectName"));
// Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectName"), Toast.LENGTH_LONG).show();
}
if (!m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase(""))
{
m_projectID_list.add(m_DepartmentDetails.getString("ProjectID"));
//Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectID"), Toast.LENGTH_LONG).show();
String strProjectID="";
String item2 = m_DepartmentDetails.getString("ProjectID");
strProjectID = item2;
}
}
}
s1 = (Spinner) findViewById(R.id.spinnerL);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spin,m_Project_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if (m_projectID_list.contains(m_ProjectID))
{
s1.setSelection(m_projectID_list.indexOf(m_ProjectID));
}
}
catch (final JSONException e)
{
}
}
}, "http://aapna.azurewebsites.net/Service1/Project", finaldata,
"POST");
connect.execute(finaldata);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
// Toast.makeText(getApplicationContext(),
// SelectedProjectID, Toast.LENGTH_LONG).show();
// Showing selected spinner item
// Toast.makeText(getApplicationContext(),
// "Selected : " + item1, Toast.LENGTH_LONG).show();
s2.setClickable(false);
s3.setClickable(false);
addItemsOnSpinner2(SelectedProjectID);
s2.setClickable(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setClickable(true);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Try this..
Change your first element from m_Project_list ArrayList as Select
And after user selecting spinner you can do other operation below codes inside onCreate
Code
s1.setSelection(0);
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
if(pos == 0){
s2.setEnabled(false);
s3.setEnabled(false);
}
else{
// do something
addItemsOnSpinner2(SelectedProjectID);
s2.setEnabled(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setEnabled(true);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
EDIT
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i("=========="," handler == > ");
Toast.makeText(getBaseContext(), "handler", Toast.LENGTH_LONG).show();
}
}, 5000);
The only solution I got is to use delay function to solve this kind of spinner as told to me by hariharan.
ADD these two statements in spinner 1 function
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id)
{
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
s2.setEnabled(false);
s3.setEnabled(false);
addItemsOnSpinner2(SelectedProjectID);
addItemsOnSpinner3(SelectedProjectID);
delay1();
//
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
then use the below function
public void delay1()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
s2.setEnabled(true);
s3.setEnabled(true);
}
}, 3000);
}
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
}
});
}
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......