In my project. I am using two Alert Dialog Box.The two alert dialogue box used in private methods. Private methods are checkIn( ) and checkOut( )
In Main Activity, I am having One Button. Two functions for the Button. One Function is Check-In and another Function is Check out.
When I went to the Activity the Button Visible in Check-in. If I click the Button. It changes into Check out and Displays the Alert Dialogue checkIn( ) private method.
If I refresh the Activity It will change into check-in.
what is my question how to get the Checkout Action when I refresh the activity.Can anyone Solve and give solution for this...
Thank you in advance. I attached the sample code below
public class Insert_DataSql extends AppCompatActivity {
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
LocationRequest locationRequest;
LocationManager locationManager;
PreparedStatement preparedStatement;
String formattedDate;
WebConnection connectionClass;
Button cin,cout;
TextView dat,tim,adddre;
Boolean flag=true;
SharedPreferences sharedPreferences;
String username;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insertdata);
connectionClass = new WebConnection();
sharedPreferences=getSharedPreferences("LoginPref", Context.MODE_PRIVATE);//here we go getdata
user name=sharedPreferences.getString("User name",null);
//Button Click able
cin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (flag) {
getMyCurrentLocation();
CheckinButton();
flag =false;
Toast.makeText(Insert_DataSql.this, "True statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");//insert for button
// tim.setText(formattedDate);
}
else{
flag =true;
getMyCurrentLocation();
CheckoutButton();
Toast.makeText(Insert_DataSql.this, "Wrong statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");
// tim.setText(formattedDate);
}
}
}
//Private methods for the Alert Dialogue box
private void CheckoutButton() {
if(flag == false ){
cin .setText("Check Out Sucessfull");
AlertDialog alertDialog = new AlertDialog.Builder(
Insert_DataSql.this).create();
alertDialog.setTitle("Check Out Sucessfully");
alertDialog.setMessage(adddre.getText());
alertDialog.setIcon(R.drawable.ic_access_time_black_24dp);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
}
private void CheckinButton() {
if(flag == true ){
cin.setText("Check Out");
AlertDialog alertDialog = new AlertDialog.Builder(
Insert_DataSql.this).create();
alertDialog.setTitle("Check In Sucessfully");
alertDialog.setMessage("Have A Nice Day");
alertDialog.setIcon(R.drawable.ic_access_time_black_24dp);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
}
Try something like this :
define those variables:
public static final String PREF_FLAG = "FLAG";
private static String COUT = "cout";
private static String CIN = "cin";
private static String defaultFlagValue = COUT;
and add those methods :
private String getFlag() {
return sharedPreferences.getString(PREF_FLAG, defaultFlagValue);
}
private void setFlag(String flag) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PREF_FLAG, flag);
editor.apply();
}
and update your code :
private void CheckinButton() {
if (getFlag() == COUT) {
...
setFlag(CIN);
}
}
private void CheckoutButton() {
if (getFlag() == CIN) {
...
setFlag(COUT);
}
}
and finally update tour onClick function
cin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (getFlag() == CIN) {
getMyCurrentLocation();
CheckinButton();
Toast.makeText(Insert_DataSql.this, "True statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");//insert for button
// tim.setText(formattedDate);
}
else{
getMyCurrentLocation();
CheckoutButton();
Toast.makeText(Insert_DataSql.this, "Wrong statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");
// tim.setText(formattedDate);
}
}
}
}
Hope it will help
Related
I am developing one app related to call block.
I have created one
dashboard activity with "three" fragment tabs. Those are like call log
tab, block tab and settings tab. I want to check the name field
condition at settings tab if valid moving to another tab otherwise
showing alert "please enter valid name". If valid name it is going to
another tab successfully. But the name is not valid i want to show
alert dialog and stay at settings tab. But i am getting twice alert
box "please enter valid name". i have checked sites but i am unable to
get the solution, please help me thanks in advance.
My code is here:
public class SettingsFragment extends Fragment{
private TabLayout tabLayout;
private ViewPager viewPager;
private View view;
private EditText et_consumerName;
DashboardActivity activity;
private static final String TAG = "SettingsFragment";
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (DashboardActivity) context;
setHasOptionsMenu(true);
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.settings_fragment_new, container, false);
et_consumerName = (EditText) view.findViewById(R.id.et_consumerName);
tabLayout = (TabLayout) activity.findViewById(R.id.tab_layout);
viewPager = (ViewPager) activity.findViewById(R.id.pager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// when user click on edit text then save button enable and
// i am getting shared preference boolean value.
boolean isSettingsChanged = TCPAApplication.mPref.getBoolean(Constants.IS_SETTINGS_CHANGED, false);
if (isSettingsChanged) {
int settingsPage = 2;
String consumerNam = et_consumerName.getText().toString().trim();
if (BuildConfig.DEBUGLINES) Log.e(TAG, "counsumer name is " + consumerNam);
if (!isConsumerNameValid(consumerNam)) {
viewPager.setCurrentItem(2);
enterFullNameAlert(getString(R.string.please_enter_firstname_and_lastname));
TabLayout.Tab tab1 = tabLayout.getTabAt(settingsPage);
tab1.select();
}
} else {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected (TabLayout.Tab tab){
}
#Override
public void onTabReselected (TabLayout.Tab tab){
}
}
});
return view;
}
private boolean isConsumerNameValid(String fName) {
if (fName.length() > 0 && fName.contains(" ")) {
return true;
}
return false;
}
}
public void enterFullNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(2);
}
});
try {
AlertDialog dialog = alertDialog.create();
dialog.setCancelable(false);
dialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
"take a global int for position of tab"
in onTabSelected method check
if(globalposition==systemTabPosition)
{
if(checkcondition)
{
tabOther.select();
globalPosition=position;
}
else
enterFullNameAlert();
}
I solved alert dialog twice problem. Thanks for giving response all.
I have taken two global variables and done the below process.
private Boolean dialogShownOnceFullName = false;
private Dialog mdialog;
private int settingsPage = 2;
public void enterFullNameAndDisplayNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(settingsPage);
}
});
try {
mdialog = alertDialog.create();
if (!mdialog.isShowing() && !dialogShownOnceFullName) {
mdialog.show();
dialogShownOnceFullName = true;
}
mdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialogShownOnceFullName = false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I have developed a show dialog alert box in a fragment. After pressing the OK button in the box, It does not exits the screen. The show dialog alert keeps prompting on the screen. I don't want to quit the app after pressing OK, but I want it to go back to the HomeScreen. How to make sure that show dialog alert box will exit the screen after pressing OK?
Here is the code
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
mStaggeredView = (StaggeredGridView) rootView.findViewById(R.id.staggeredview);
mStaggeredView.setOnScrollListener(scrollListener);
sharedPreference = new SharedPreference();
// iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
if(photoUrl==null){
Toast.makeText(getActivity(),"no favourite list",Toast.LENGTH_SHORT).show();
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (photoUrl.length == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
}
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
if(text==null){
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
else {
StaggeredGridViewItem item;
item = new FavouriteGridItem(getActivity(), photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
}
// URL url = null;
// try {
// url = new URL(text);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
// iv.setImageBitmap(bmp);
return rootView;
}
private void showAlert(String string, String message) {
if (getActivity() != null && !getActivity().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//getActivity().finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
public void onTop() {
}
public void onScroll() {
}
public void onBottom() {
}
};
#Override
public void onResume() {
super.onResume();
}
}
Hey every one has i am create rename application in android ,I will set a Edit-text box in set error message using without toast using Alert Dialog box
Sample Code :
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.rename_title);
folderManager = new FolderManager(getActivity());
folderManager.open();
Cursor c = folderManager.queryAll(itemPos);
if (c.moveToFirst()) {
do {
Newnamefolder = c.getString(1);
} while (c.moveToNext());
}
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(Newnamefolder);
alert.setView(input);
alert.setPositiveButton(R.string.rename_position_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Newnamefolder = input.getText().toString();
String Mesage_one = getResources().getString(R.string.folder_already_exit);
String Mesage_two = getResources().getString(R.string.types_minimum_eight_charcter);
String Mesage_three = getResources().getString(R.string.folder_empty);
String Matchnamerename = folderManager.getmatchfoldername(Newnamefolder);
if(Newnamefolder.equals(Matchnamerename))
{
input.setError(Mesage_one);
}
else if(Newnamefolder.length()>12)
{
input.setError(Mesage_two);
}
else if(Newnamefolder.equals(""))
{
input.setError(Mesage_three);
}
else
{
int newfolder = folderManager.update(itemPos,Newnamefolder);
reload();
}
}
});
alert.show();
But the problem once in click the OK button Don't show error message to exit the Alert Dialog box...
give me any solution ... Friends ?
You can extend Dialog and create your own dialog
public class CustomDialog extends Dialog implements View.OnClickListener {
private boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
Button positive = (Button) findViewById(R.id.button_positive);
Button negative = (Button) findViewById(R.id.button_negative);
EditText field = (EditText) findViewById(R.id.field);
positive.setOnClickListener(this);
negative.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_positive:
onPositiveButtonClicked();
break;
case R.id.button_negative:
//onNegativeButtonClicked();
break;
}
}
private void onPositiveButtonClicked() {
if(verifyForm()) {
success = true;
dismiss();
}
}
public boolean isSuccess() {
return success;
}
private boolean verifyForm() {
boolean valid = true;
/* verify each field and setError() if not valid */
if(!TextUtils.isEmpty(field.getText())) { //or any other condition
valid = false;
field.setError("error message");
}
return valid;
}
}
You can show your CustomDialog like this
final CustomDialog customDialog = new CustomDialog();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(customDialog.isSuccess()) {
//update your folder manager
}
}
}
customDialog.show();
i've recently started developing in android and am currently stuck at a point i need to receive values from a dialog box. I have a mainActivity which extends fragmentActivity and an AlertDialog Class.
1)i created a static method showDefalutDialog in AlertDialog class and its being called from mainActivity button click listener with parameters being passed to alertDialog.
2)In showDefalutDialog static method i created .setPositivebutton and .setNegativeButton with a Yes/No DialogInterface respectively.
now here's what i want to do.
1)When yes button on interface is clicked it should return a value to mainActivity
so i can implement it in an if statement to perform a certain function.
moving from windows c# programming doing so isn't a problem but i just don't know how to implement that in android below is relevant code snip
private void sendSms()
{
SharedPreferences pref = getApplicationContext().getSharedPreferences("Sms_MyPref", 0);
mail = pref.getString("email", null); // getting String
tel = pref.getString("receiver_tel", null); // getting String
layout = (LinearLayout)findViewById(R.id.linearLayout1);
from_dateEdit = (EditText) findViewById(R.id.date_edit);
to_dateEdit = (EditText) findViewById(R.id.date_edit_to);
snButton = (Button)findViewById(R.id.form_send_button);
from = (Button)findViewById(R.id.from);
to = (Button)findViewById(R.id.to);
spn = (Spinner)findViewById(R.id.form_spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
spinnerV = (String) item;
if(pos == 0)
{
layout.setVisibility( pos == 0 ? View.VISIBLE : View.VISIBLE);
from_dateEdit.setText(DatePickerFragment.getYesteesDate());
from.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker();
}
});
to_dateEdit.setText(DatePickerFragment.getTodaysDate());
to.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker2();
}
});
new1 = null;
new2 = null;
from_dateEdit.setText(new1);
to_dateEdit.setText(new2);
}
else if(pos == 1)
{
layout.setVisibility( pos == 1 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 2)
{
layout.setVisibility( pos == 2 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 3)
{
layout.setVisibility( pos == 3 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
snButton.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
if(new1 == null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date range", false);
}
else if(new1 != null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date TO", false);
}
else if(new1 == null && new2 != null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date FROM", false);
}
else
{
gen = new1.toString()+","+new2.toString();
alert();
//i want to return a value from dialog yes/no click
if(/*dialog yes is clicked*/)
{
sms();
}
else if(/*dialog No is clicked*/)
{
return;
}
}
}
});
}
private void alert()
{
AlertDialogManager.showDefalutDialog(getApplicationContext(), spinnerV, mail, new1,new2);
}
public void sms()
{
String both = "{"+ spinnerV.toString() + ","+gen.toString()+","+ mail.toString()+"}";
sendSMS(tel,both);
}
and showDefaultDialog static method from AlertDialog class
#SuppressLint("InflateParams")
public static void showDefalutDialog(final Context context, String order, final String mail, String fromD, String toD) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.finalmsg);
LayoutInflater li = LayoutInflater.from(context);
View view = li.inflate(R.layout.data_summary_view, null);
EditText EMAIL = (EditText)view.findViewById(R.id.Email);
EditText Selectedorder = (EditText)view.findViewById(R.id.order);
EditText Dfrom = (EditText)view.findViewById(R.id.edit_from);
EditText Dto= (EditText)view.findViewById(R.id.edit_to);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.datelayout);
LinearLayout l2 = (LinearLayout) view.findViewById(R.id.datelayout2);
Selectedorder.setText(order);
EMAIL.setText(mail);
if(fromD.toString() != "a" && toD.toString() != "b")
{
ll.setVisibility(View.VISIBLE);
l2.setVisibility(View.VISIBLE);
Dfrom.setText(fromD);
Dto.setText(toD);
}
else if(fromD.toString() == "a" && toD.toString() == "b")
{
ll.setVisibility(View.GONE);
l2.setVisibility(View.GONE);
}
// set dialog message
alertDialogBuilder.setView(view);
//int msdt = data.toString().toCharArray().length;
//Toast.makeText(context, "MsData char count : " + msdt , Toast.LENGTH_SHORT).show();;
alertDialogBuilder
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
try {
Intent main = new Intent(context, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(main);
} catch (Exception e) {
Log.d(TAG, "Error while starting Main activity from Dialog ! ");
}
}
})
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(context,"Your Order will be sent to "+ mail +" please check your inbox for comfirmation." , Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
You can define you custom interface simmilar to this one:
public interface MyDialogClickListener {
void onPositiveClicked(String value);
}
Then you create instance and pass to method, where you create dialog:
public static void showDeafultDialog(..., MyDialogClickListener listener) {
// ...
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listener.onPositiveClicked("you can pass yout value here")
}
})
// ...
}
Handle result:
private void sendSms() {
AlertDialogManager.showDeafultDialog(..., new MyDialogClickListener() {
#Override
public void onPositiveClicked(String value) {
// do whatever you want with value
}
});
I'm writing an app where the user describes a problem and then receives advice. The user presses a button which shows a dialog with an EditText. Once the user presses OK, I want to get their input, but I'm having trouble with the extras. I've read similar questions, but I can't seem to find the problem. On a summary screen where I display the information, no text ever appears. Any help is appreciated!
I think the problem is when I call getText() on the EditText. Using log.d the mText is just an empty String.
Here is my code:
The fragment AdviceFragment from which the dialog is called:
private static final String DIALOG_TEXT = "text";
private static final int REQUEST_TEXT = 0;
private Advice mAdvice;
private boolean hasText;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
...
mTextButton = (Button) v.findViewById(R.id.textButton);
mTextButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
FragmentManager fm = getActivity().getSupportFragmentManager();
InputTextFragment dialog = new InputTextFragment();
dialog.setTargetFragment(AdviceFragment.this, REQUEST_TEXT);
dialog.show(fm, DIALOG_TEXT);
}
});
}
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != Activity.RESULT_OK)
{
return;
}
if (resultCode == REQUEST_TEXT)
{
String text = data.getStringExtra(InputTextFragment.EXTRA_TEXT);
if (text.length() > 0)
{
mAdvice.setText(text);
hasText = true;
}
else
{
mAdvice.setText(null);
hasText = false;
}
}
InputTextFragment dialog:
public class InputTextFragment extends DialogFragment
{
public static final String EXTRA_TEXT = "text";
private String mText;
private void sendResult(int resultCode)
{
if (getTargetFragment() == null)
{
return;
}
Intent i = new Intent();
i.putExtra(EXTRA_TEXT, mText.toString());
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_input_text, null);
final EditText editText = new EditText(getActivity());
return new AlertDialog.Builder(getActivity())
.setView(v)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int whichButton)
{
String input = editText.getText().toString();
if (input.length() > 0)
{
mText = input;
}
else
{
return;
}
sendResult(Activity.RESULT_OK);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
{
...
})
.create();
}
}
final EditText editText = new EditText(getActivity());
You problem is here, your EditText is not added to your Dialog's View Tree. I think you should do like this:
final EditText editText = (EditText)v.findViewById(your_edittext_id);
Thanks, I think this has fixed part of the problem. Using log.d in the
onClick() method of setPositiveButton()shows that it is successfully
assigning the value. However, I'm still not getting anything when I
call onActivityResult(). Do you have any idea what's going wrong?
Look here, another typo problem:
if (resultCode == REQUEST_TEXT)
{
It should be requestCode.
I think this should fix your problem, but you'd better follow bean_droid's suggest and use an interface instead of calling the onActivityResult() method. It's because that method may be called by other part of your code, which you don't want.
Here try this:
Public class AdviceFragment extends Fragment implements OkClickListener{
#Override
Public void onClick(String data){
//DO YOUR CODE HERE
}
}
InputTextFragment
Public Class InputTextFragment extends DialogFragment{
public interface OkClickListener{
public void onClick(String data);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_input_text, null);
final EditText editText = new EditText(getActivity());
return new AlertDialog.Builder(getActivity())
.setView(v)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int whichButton)
{
String input = editText.getText().toString();
if (input.length() > 0)
{
mText = input;
}
else
{
return;
}
((OkClicklistener)getTargetFragment()).onClick(data);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
{
...
})
.create();
}
}
}
replace sendResult(Activity.RESULT_OK); to getActivity().setResult(resultCode);