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.
Related
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 :)
Please help me with little thing that make me crazy
I’m trying to set text in a textview that is the last element of a dynamic Array.
I add a function inside my Adapter that return the last element of the array.
I’m coming back to the Main Activity where I’d like to show the text and during time it falls at “nullpointerexception”.
Please help
Here is my code:
public class MainActivity extends Activity implements OnClickListener{
private static Context mContext;
public Button mExit, mHistory, mRating;
public TextView mSignal;
HistoryAdapt myLastItem;
List<HistoryItems> m_myLastItem;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext=getApplicationContext();
mExit=(Button)findViewById(R.id.ExitButton);
mExit.setOnClickListener(this);
mHistory=(Button)findViewById(R.id.HistoryButton);
mHistory.setOnClickListener(this);
mRating=(Button)findViewById(R.id.RateButton);
mRating.setOnClickListener(this);
mSignal=(TextView)findViewById(R.id.SignalOfTheDayTV);
//### SET LAST ELEMENT INTO TEXTVIEW
m_myLastItem = new ArrayList<HistoryItems>();
myLastItem=new HistoryAdapt(mContext, m_myLastItem );
m_myLastItem= (List<HistoryItems>) myLastItem.getLastElement();
mSignal.setText(( (HistoryItems) m_myLastItem).getTitle());
// AppRater.app_launched(this);
// AppRater.showRateDialog(this, null);
//Get a Tracker (should auto-report)
((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
}//oncreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static Context getAppContext(){
return MainActivity.mContext;
}
public void ExitState(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("You're about to quit Signals4Trading");
builder.setIcon(R.drawable.five);
//builder.setMessage("Your device has been registered successfully. You'll receive signals very soon.");
builder.setMessage("Are you sure you want to quit?");
builder.setCancelable(false);//can't click on the background of the activity
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"See you soon", Toast.LENGTH_LONG).show();
finish();
}//OnClickListener PositiveButton
});//anonymous class PositiveButton
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Enjoy your visit", Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}//ExitState
public void goToHistoryActivity(){
Intent intent = new Intent(MainActivity.this, HistoryAct.class );
startActivity(intent);
}
public void rateApp(){
Intent intent = new Intent(MainActivity.this, Rate.class);
startActivity(intent);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.ExitButton:
ExitState();
break;
case R.id.HistoryButton:
goToHistoryActivity();
break;
case R.id.RateButton:
rateApp();
break;
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Get an Analytics tracker to report app starts & uncaught exceptions etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//Stop the analytics tracking
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
}//MainActivity
**Adapter:**
package com.Signals4Trading.push.android;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class HistoryAdapt extends BaseAdapter {
private final List<HistoryItems>items;
private final Context context;
public HistoryAdapt(Context context,List<HistoryItems>items){
this.context=context;
this.items=items;
}//constructor
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int id) {
// TODO Auto-generated method stub
return id;
}
//###FUNCTION THAT RETURN LAST ELEMENT
public HistoryItems getLastElement(){
HistoryItems lastItem = items.get(items.size());
if(items!=null && !items.isEmpty()){
lastItem = items.get(items.size()-1);
}
return lastItem;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.historyitems, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitleTV);
holder.itemDate=(TextView) convertView.findViewById(R.id.itemDateTV);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
holder.itemDate.setText(items.get(position).getDate());
return convertView;
}
class ViewHolder {
TextView itemTitle;
TextView itemDate;
}
}
//HistoryAdapt
you are getting this error because you have never intialized the object of your adapter class
HistoryAdapt in requires a context and and list to pass into it ,as defined in your constructor
This may be because Listitems is still referencing to null object. Have you called HistoryAdapt(context,items) constructor before calling
HistoryItems l_myLastItem= (HistoryItems) myLastItem.getLastElement(0);
?
Do as Haresh Chhelana said
public HistoryItems getLastElement(){
return items.get(items.size()-1);
}
the reason you are getting null pointer exception is because your list has not been initialized so it is referencing null. To get rid of this error you should first initialize your ArrayList then populate it as
//### SET LAST ELEMENT INTO TEXTVIEW
m_myListItem = new ArrayList();
//then add some data to arrayList for eg:
for (i=1;i<=10;i++){
m_myListItem.add(new HistoryItem().setTitle("title " + i));
}
myLastItem=new HistoryAdapt(mContext, m_myListItem ); //this should be m_myListItem not m_myLastItem
m_myLastItem= myLastItem.getLastElement();// m_myLastItem should be of type HistoryItem as HistoryItem m_myLastItem not List<HistoryItems> m_myLastItem
mSignal.setText(m_myLastItem.getTitle());
P.S. please have a look at your variable naming convention
No need to pass last item index instead directly get index from adapter list size.
public HistoryItems getLastElement(){
return items.get(items.size()-1);
}
Firstly, this is my first question here, Thanks for any reply:)
I have a fragment extends SherlockListFragment that has a list of (events) saved in database, i want when i click on any item in the list , to get all event data and fill in another activity that has editText(s) ....
this is the frgment.java code
public class EventsFragment extends SherlockListFragment {
EditText _eventName_;
EditText next_activty_text;
List<String> presidents = new ArrayList<String>();
public DBAdapter db;
String buf = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_events, container, false);
_eventName_ = (EditText) v.findViewById(R.id.editText11);
next_activty_text = (EditText) v.findViewById(R.id.editText12);
// The most Important part in action bar menus :)
setHasOptionsMenu(true);
/*
//This is how to link a button in fragment by its .xml file :Ds
Button create_btn = (Button) v.findViewById(R.id.button1);
create_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
}
});*/
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
db = new DBAdapter(getActivity());
db.open();
int i = 1;
while(db.getEvent(i).isLast()){
Cursor c = db.getEvent(i);
presidents.add(c.getString(1));
i++;
}
db.close();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_events_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
startActivity(new Intent("com.nazmy.CreateEventActivity"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
//populate(c.getString(1));
_eventName_.setText(c.getString(1));
db.close();
}
}
`
and this is the activity code
public class CreateEventActivity extends FragmentActivity {
EditText mEdit;
EditText mEdit2;
EditText mEditFromTime;
EditText mEditToTime;
int whichDateBtn;
int whichTimeBtn;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
db.open();
Cursor c = db.getAllEvents();
if (c.moveToFirst())
{
do {
DisplayEvent(c);
} while (c.moveToNext());
}
db.close();
Button cancel_btn = (Button) findViewById(R.id.button4);
Button save_btn = (Button) findViewById(R.id.button1); //if clicked -> save in data-base
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
EditText event_name = (EditText)findViewById(R.id.editText12);
EditText event_place = (EditText)findViewById(R.id.editText13);
EditText from_date = (EditText)findViewById(R.id.editText14);
EditText from_time = (EditText)findViewById(R.id.editText15);
EditText to_date = (EditText)findViewById(R.id.EditText16);
EditText to_time = (EditText)findViewById(R.id.EditText17);
CheckBox share = (CheckBox)findViewById(R.id.checkBox1);
CheckBox alarm = (CheckBox)findViewById(R.id.checkBox2);
long id2 = db.insertEvent(event_name.getText().toString(), event_place.getText().toString(),
from_date.getText().toString(), to_date.getText().toString(),
from_time.getText().toString(),
to_time.getText().toString(),
share.isChecked(),alarm.isChecked());
db.close();
event_name.setText("");
event_place.setText("");
from_date.setText("");
to_date.setText("");
from_time.setText("");
to_time.setText("");
if (share.isChecked()) {
share.setChecked(false);
}
if (alarm.isChecked()) {
alarm.setChecked(false);
}
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
}
//This method shows the dialog when Button is clicked
public void selectFromtDate(View view) {
DialogFragment mDialog = new SelectDateFragment();
mDialog.show(getFragmentManager(), "DatePicker");
whichDateBtn = 0;
}
public void selectToDate(View view) {
DialogFragment mDialog2 = new SelectDateFragment();
mDialog2.show(getFragmentManager(), "DatePicker");
whichDateBtn = 1;
}
//This method will update the EditText field with the following code.
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText14); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEdit2 = (EditText)findViewById(R.id.EditText16);
if(whichDateBtn==0) {
mEdit.setText(month+"/"+day+"/"+year);
}
else if (whichDateBtn == 1) {
mEdit2.setText(month+"/"+day+"/"+year);
}
}
//This subclass includes method to display the datepicker fragment to the user.
//It also has the method to handle the event on setting the date.
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
//The onCreateDialog() method creates a calendar object.
//Using this object the current day, month and year that will be retrieved.
//This current instance will return to the activity to display the date picker with the current date by default.
//onDateSet() method calls the populateSetDate() with the selected date parameters.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Time Pickers
////////////////////////////////////////////////////////////////////////////////////////////////////////
public void selectFromTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 0;
}
public void selectToTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 1;
}
public void populateSetTime(int hour, int min) {
mEditFromTime = (EditText)findViewById(R.id.editText15); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEditToTime = (EditText)findViewById(R.id.EditText17);
if(whichTimeBtn==0) {
mEditFromTime.setText(hour+":"+min);
}
else if (whichTimeBtn == 1) {
mEditToTime.setText(hour+":"+min);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
populateSetTime(hourOfDay, minute);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_create_event, menu);
return true;
}
public void DisplayEvent(Cursor c)
{
Toast.makeText(this,
"id : " + c.getString(0) + "\n" +
"Event Name: " + c.getString(1) + "\n" +
"Place : " + c.getString(2) + "\n" +
"From Date : " + c.getString(3)+ "\n" +
"From Time : " + c.getString(5)+ "\n" +
"To Date : " + c.getString(4)+ "\n" +
"To Time : " + c.getString(6),
Toast.LENGTH_LONG).show();
}
}
`
Thanks in advance :)
You have two choices. Either fetch the data from your database in EventsFragment.onListItemClick(), and pass that data to your second Activity as Intent extras. Or you can pass the id of the clicked item, and do the database operations in your second Activity. Either way you have to pass data using Intents
public class EventsFragment extends SherlockListFragment {
.
.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, CreateEventActivity.class);
// OPTION 1: Fetch data here, and pass it with the intent
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
intent.putExtra("id", c.getString(1));
intent.putExtra("event_name", c.getString(2));
// Do this for all your values.
db.close();
startActivity(intent);
// OPTION 2: Pass the id of the selected item, and fetch the data in second activity
intent.putExtra("selected_id", id+1);
startActivity(intent);
}
}
In CreateEventActivity you then have to get the extras you chose to pass with the Intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
Intent intent = getIntent();
// If you chose option 1, you have to get all the extras you attached to the Intent.
long id = intent.getLongExtra("id", -1)
String eventName = intent.getStringExtra("event_name", "defValue");
// Fetch all the values here..
// If you chose option 2, you fetch the id and do the database operations to retrive
// the data
long id = intent.getLongExtra("selected_id", -1);
// DB stuff here..
}
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
}
});
}
I implement a TabActivity (TabHost) with ActivityGroup based on this website http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html
I have 2 questions about implement this.
First question, Using TabActivity with PreferenceActivity, error occurs when I click an preference item to make a preference dialog.
08-10 21:55:35.919: E/AndroidRuntime(1415): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#405296f0 is not valid; is your activity running?
I found a solution that I should use "getParent()" instead of "getApplicationContext()"or"this" in my code, but I don't know where/how to do it? I don't know how to do something like "setContext(getParent())" with my PreferenceActivity.
I have a problem exactly same as this: TabActivity with ActivityGroup and PreferenceActivity child
Here is my code:
public class MoreUserProfile extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.more_userprofile);
}
In my opinion, I think I should implement something in a dialog class, in onCreateDialogView() because android calls this method at making dialog time. I try my best but I can't solve my problem
public class MoreUserProfileDateOfBirthDialog extends DialogPreference {
LinearLayout layout;
SharedPreferences.Editor editor;
public MoreUserProfileDateOfBirthDialog(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setDialogLayoutResource(R.layout.more_userprofile_dialog_dateofbirth);
}
#Override
protected View onCreateDialogView() {
// TODO Auto-generated method stub
// I think I should implement some code here.
//Activity parent = new Activity();
//LayoutInflater inflater = (LayoutInflater) parent.getLayoutInflater();
//layout = (LinearLayout) inflater.inflate(R.layout.more_userprofile_dialog_dateofbirth, null);
}
protected void onBindDialogView(View view) {
layout = (LinearLayout) view.findViewById(R.id.more_userprofile_dialog_dateofbirth_linearlayout);
SharedPreferences pref = getSharedPreferences();
int day = pref.getInt("dayOfBirthday", 1);
int month = pref.getInt("monthOfBirthday", 1);
int year = pref.getInt("yearOfBirthday", 2000);
DatePicker dp = (DatePicker) view.findViewById(R.id.more_userprofile_dialog_choosedateofbirth_datePicker);
dp.init(year, month-1, day, onDateChangedListener);
layout.removeAllViews();
layout.addView(dp);
super.onBindDialogView(view);
}
DatePicker.OnDateChangedListener onDateChangedListener = new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
editor = getEditor();
editor.putInt("dayOfBirthday", view.getDayOfMonth());
editor.putInt("monthOfBirthday", view.getMonth()+1);
editor.putInt("yearOfBirthday", view.getYear());
}
};
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
super.onClick(dialog, which);
if(which==DialogInterface.BUTTON_NEGATIVE){
dialog.dismiss();
}
if(which==DialogInterface.BUTTON_POSITIVE){
editor.commit();
}
}
}
Second question, Similar as Above, but this time is about TabActivity with ListView Adapter (Use for Custom Listview). On each Custom Listview item has 2 buttons, "Edit" and "Delete". When I click on one of these button, dialog appears. But after I apply TabActivity to my application, I got an error when press these button. The error code is similar as above:
08-10 22:13:56.643: E/AndroidRuntime(1427): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#40526c50 is not valid; is your activity running?
Here is my code:
public class ActivityListviewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
private ArrayList<Activities> listData = new ArrayList<Activities>();
public ActivityListviewAdapter(Context context,ArrayList<Activities> listData,) {
// TODO Auto-generated constructor stub
super();
this.context = context;
this.mInflater = LayoutInflater.from(context);
this.listData = listData;
}
public int getCount() {
// TODO Auto-generated method stub
return listData.size(); //ส่งขนาดของ List ที่เก็บข้อมุลอยู่
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ActivityRowList activitylist;
if(convertView == null){
convertView = mInflater.inflate(R.layout.more_customizedactivity_customlistview, null);
activitylist = new ActivityRowList();
activitylist.ActivityName = (TextView) convertView.findViewById(R.id.TextView_More_Customizedactivity_Customlistview_ActivityName);
activitylist.ActivityDetail = (TextView) convertView.findViewById(R.id.TextView_More_Customizedactivity_Customlistview_ActivityDetail);
activitylist.ActivityType = (ImageView) convertView.findViewById(R.id.ImageView_Activity_ShowallActivity_Customlistview);
activitylist.EditCustomizedButton = (Button) convertView.findViewById(R.id.Button_More_Customizedactivity_Customlistview_Edit);
activitylist.DeleteCustomizedButton =(Button)convertView.findViewById(R.id.Button_More_Customizedactivity_Customlistview_Delete);
convertView.setTag(activitylist);
}else{
activitylist = (ActivityRowList) convertView.getTag();
}
activitylist.ActivityName.setText(listData.get(position).getActivityName());
activitylist.ActivityDetail.setText("MET: "+listData.get(position).getActivityMET().toString());
activitylist.ActivityType.setImageResource(R.drawable.activity_type_customized);
activitylist.EditCustomizedButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editNewActivityDialog(listData.get(position).getActivityName(), listData.get(position).getActivityMET(),position);
}
});
activitylist.DeleteCustomizedButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
confirmDeleteCustomizedDialog(listData.get(position).getActivityName(),listData.get(position));
}
});
return convertView;
}
private void confirmDeleteCustomizedDialog(final String ActivityNameInput,final Activities listDataposition){
// TODO Auto-generated method stub
AlertDialog alertDialog = new AlertDialog.Builder(mInflater.getContext()).create();
alertDialog.setTitle("Confirm Delete");
alertDialog.setMessage("Do you want to delete:\"" + ActivityNameInput +"\"" );
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Some codes here
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialog.show();
}
private void editNewActivityDialog(final String ActivityNameBefore, float ActivityMETBefore,final int ListPosition) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(mInflater.getContext());
dialog.setContentView(R.layout.more_customizedactivity_dialog_addnew);
final EditText EditText_Addnewactivity_Dialog_ActivityName=(EditText)dialog.findViewById(R.id.EditText_More_Customizedactivity_Addnewactivity_Dialog_ActivityName);
final EditText EditText_Addnewactivity_Dialog_ActivityMET=(EditText)dialog.findViewById(R.id.EditText_More_Customizedactivity_Addnewactivity_Dialog_ActivityMET);
final Button Button_More_Customizedactivity_Addnewactivity_Dialog_OK=(Button)dialog.findViewById(R.id.Button_More_Customizedactivity_Addnewactivity_Dialog_OK);
final Button Button_More_Customizedactivity_Addnewactivity_Dialog_Cancel=(Button)dialog.findViewById(R.id.Button_More_Customizedactivity_Addnewactivity_Dialog_Cancel);
dialog.setTitle("Edit Activity by User");
EditText_Addnewactivity_Dialog_ActivityName.setText(ActivityNameBefore);
EditText_Addnewactivity_Dialog_ActivityMET.setText(ActivityMETBefore+"");
dialog.show();
Button_More_Customizedactivity_Addnewactivity_Dialog_OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Some codes here
});
Button_More_Customizedactivity_Addnewactivity_Dialog_Cancel.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
}
According to my code:
When I press "Edit" on my custom listview, code runs editNewActivityDialog() method and builds Dialog by using this:
final Dialog dialog = new Dialog(mInflater.getContext());
(I think I should change "mInflater.getContext()" to something else but I don't know.)
When I press "Delete" button on my custom listview, code runs confirmDeleteCustomizedDialog() method and builds AlertDialog by using this:
AlertDialog alertDialog = new AlertDialog.Builder(mInflater.getContext()).create();
(I think I should change "mInflater.getContext()" to something else but I don't know.)
Very thanks in advance :)