I am new to android development, I have got an weather app, My WeatherFragment class got below code, which is of a fragment class.
btn=(Button)rootView.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Change city");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity obj=new MainActivity();
obj.changeCityLocation(input.getText().toString());
}
});
builder.show();
}
});
return rootView;
}
and I need to call changeCityLocation() which is in MainActivity, which code is:
public void changeCityLocation(String city){
WeatherFragment wf = (WeatherFragment)getSupportFragmentManager()
.findFragmentById(R.id.container);
wf.changeCity(city);
new CityPreference(this).setCity(city);
}
I need to take the input and store in city variable when I click ok but it crashed. Thank you all in advance.
You are doing wrong here
MainActivity obj=new MainActivity();
Because this is not possible. All Activities in android must go through the Activity lifecycle so that they have a valid context attached to activity. so you have to use getActivity() method to get parent activity object and then cast it to MainActivity. like this
((MainActivity) getActivity()).changeCityLocation(input.getText().toString());
This will allow you to access Parent activity methods from fragment.
Related
Please help me guys. I tried to put SetCancelable(false) in dialogfragment but still not working.
this is my DialogFragment:
public static class UsageAcessDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Grant Usage Access permission")
.setTitle("Usage Access Permission")
.setCancelable(false)
.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
startActivityForResult(
new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),
MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Thank you for those who will comment.
You dont need to builder! you are inside dialog fragment
try this one setCancelable(false)
insted of using builder.setCancelable(false)
You don't need to associate setCancelable with the builder. write setCancelable method directly because you are inside a DialogFragment
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle("Usage Access Permission");
builder.setMessage("Grant Usage Access permission");
setCancelable(false); // this line
builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
tartActivityForResult(
new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),
MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
}
});
return builder.create();
}
I want to finish the activity when custom dialog is cancelled or dismissed. But when I use .setOnDismissListener in other classes, it is never being reached inside. I've found several problems, but the solution was to override onDismiss method inside the customDialog class. But I do not need to override onDismiss method for every customDialog I create. What should I do?
This is the code I call in another class, but never receive message in log "setOnDismissListener".
customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "setOnDismissListener");
}
});
My CustomDialog class:
public class CustomDialog extends Dialog {
private static final String TAG = "CustomDialog";
public CustomDialog(Context context, String title, String message) {
super(context);
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
}
}
Yeah, so if you are not using some API to parse information, or are using local variables I suggest you do whatever functionality you want to do in your onClickListener() Method.
The problem is that you are using your CustomDialog which itself extends the Dialog Class. But instead of using that you create a new alert dialog and build that. You dismiss it, but the dialog which is dismissed is not your custom dialog class, but the builder dialog you created in your constructor. Even if you fixed for that, it introduces unnecessary complications.
What I suggest you do is create the Intent in your onClickListener() function. The way to do that would be to change your constructor to support a callback listener. Simply put you cannot just add an onDismissListener() when the dialog you listen to is another one. What you can do is pass in the function that you want to do when the user dismisses the dialog as a special case. See below.
So, first, modify your constructor like this:
public CustomDialog(Context context, String title, String message,
DialogInterface.OnClickListener listener) {
super(context);
}
In your constructor paste your previous code:
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok", listener);
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
What you do is where you used to create a new onClickListener() you pass in the listener parameter.
Go to your MainActivity or where you create your custom dialog. There do this:
CustomDialog customDialog = new CustomDialog(FirstActivity.this, "Title", "Message",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do your functionality here.
Intent intent = new Intent(context, activity.class);
//Add any flags if you want
...
context.startActivity(intent);
//Or you can simply do context.finish();
}
});
When you don't want to pass a onClickListener()(meaning when you don't want to finish() the activity) pass in null.
It would work. If this is not what you wanted, tell me and I will fix it.
Make an interface like
interface OnUserInformedCallback {
fun positive()
fun negative()
}
and implement this in your activity and pass it to the dialog method from where you are gettingdialog and you will get callback of ok and cancle in you activity.
code is like that
fun alertDialog(
context: Context,
message: String,
positiveText: String,
isUa: Boolean,
callback: OnUserInformedCallback
): Dialog {
val dialog = Dialog(context, android.R.style.Theme_Translucent_NoTitleBar)
dialog.setContentView(R.layout.alert_dialog_layout)
dialog.window?.setGravity(Gravity.CENTER)
dialog.setCancelable(true)
dialog.setCanceledOnTouchOutside(true)
val tvOk: TextView = dialog.findViewById(R.id.visit)
val tvMsg: TextView = dialog.findViewById(R.id.mess)
tvMsg.text = message
tvOk.text = positiveText
dialog.findViewById<TextView>(R.id.cancel).setOnClickListener {
callback.negative()
}
tvOk.setOnClickListener {
callback.positive()
}
dialog.create()
return dialog
}
in java for default dialog
private AlertDialog getDialog(Activity context, String message, OnUserInformedCallback callbac) {
return new AlertDialog.Builder(context)
.setTitle(R.string.app_name).setMessage(message)
.setCancelable(true)
.setPositiveButton(android.R.string.yes, (dialog12, which) -> callbac.positive())
.setNegativeButton(android.R.string.yes, (dialog1, which) -> callbac.positive())
.create();
}
I'm trying to set the linktextcolor of the message in AlertDialog. But when I try to findViewById my app crashes. What am I doing wrong? Do I need to have message in the XML for the activity?
final AlertDialog d = new AlertDialog.Builder(new ContextThemeWrapper(SplashPage.this, R.style.Theme_Sherlock_Light_Dialog))
.setIcon(android.R.drawable.ic_dialog_info).setTitle(getString(R.string.termsTitle))
//.setView(message).setCancelable(false)
.setMessage(Html.fromHtml(getString(R.string.terms))).setCancelable(false)
.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
app.setTermsAccepted(true);
dialogInterface.dismiss();
Intent intent = new Intent(SplashPage.this, LoginPage.class);
startActivity(intent);
}
}).create();
//FAILING: TextView TV = (TextView)d.findViewById(android.R.id.message);
//TV.setLinkTextColor(Color.MAGENTA);
I looked at the AlertDialog documentation and it appears that when you call its method, it searches an XML that you've processed in its onStart method (http://developer.android.com/reference/android/app/Dialog.html#findViewById%28int%29). Instead, simply call your activity's findViewById method (e.g. if this is in an activity class, just calling:
TextView TV = (TextView) findViewById(android.R.id.message);
should work.)
If you are using a DialogFragment, it is accessible after DialogFragment.onStart() method as eluded to in the prior answer.
#Override
public void onStart() {
super.onStart();
final TextView textView = (TextView) getDialog().findViewById(android.R.id.message);
//Do something!
}
I have the following code which displays a dialog box to the user if no network connection is detected.
private void createNoNetworkDialog() {
LayoutInflater inflater = LayoutInflater.from(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = inflater.inflate(R.layout.offline_mode_dialog,null);
builder.setView(view);
builder.show();
}
There are two buttons in this dialog which have methods defined for their onClick actions. I would like to close the dialog pop-up after either of these button is pressed. Any ideas??
Yes,call dismiss() from the Listener's onClick since the DialogInterface reference is passed, which allows for dismissal.
Eg
builder.setPositiveButton ("Yes", new DialogInterface.OnClickListener()
{
public void onClick (DialogInterface dialog, int which)
{
//do stuff beforehand
dialog.dismiss();
}
});
Or if your buttons are inside the layout, show the dialog and keep a reference to it (final AlertDialog dialog = builder.show()). Then use dialog.findViewById() to find the respective buttons. Assign a normal View.OnClickListener and in it call dismiss() using the dialog reference you're holding.
Try this, Am using custom layout its working for me. inilitized Button custon_dialog.findViewById() and then write OncliclListner(). It will work
final Dialog custon_dialog = new Dialog(Login.this);
custon_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
custon_dialog.setContentView(R.layout.forget_custom_dialog);
custon_dialog.setCancelable(true);
Button submit_Btn = (Button) custon_dialog
.findViewById(R.id.submit);
Button cancel_Btn = (Button) custon_dialog
.findViewById(R.id.cancel);
submit_Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do your stuf
}
});
cancel_Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
custon_dialog.dismiss();
}
});
custon_dialog.show();
}
I am developing an android application. Now i have created one function which create custom dialog box and i want this dialog box to display on every activity. So i need to call this function at every activity. But as the syntax of custom dialog (e.g. Dialog d = new Dialog(home.this)).home is the name of the activity where i have created the function so i am not ale to use this function in any other activity. And i haven't use android that much. So give me good example to solve my problem. Here is my code
here is sample code code of using AlertDialog in all activity.
crate one class file like as allmethod.java
and add this code in that class
public static void showAlert(Activity act,String msg)
{
AlertDialog.Builder alert = new AlertDialog.Builder(act);
alert.setMessage(msg).setPositiveButton("OK", new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which)
{
}
}).show();
}
and you can use from any class like as
allmethod.showAlert(Activity,"Message");
In your case..
public void SearchDialog(Context ctx){
final Dialog dialog = new Dialog(ctx);
dialog.setContentView(R.layout.dialogsearch);
dialog.setTitle(" Enter The Text to Search");
dialog.setCancelable(true);
final EditText Text = (EditText) dialog.findViewById(R.id.EdText);
Button buttonOK = (Button) dialog.findViewById(R.id.btnOK);
buttonOK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String SearchText = Text.getText().toString();
prefsPrivate =getSharedPreferences(Login.PREFS_PRIVATE,Context.MODE_PRIVATE);
Editor prefsPrivateEdit=prefsPrivate.edit();
prefsPrivateEdit.putString("Text",SearchText);
prefsPrivateEdit.commit();
Intent i = new Intent(ctx,SearchTask.class);
startActivity(i);
dialog.cancel();
}
});
Button buttonCancel = (Button) dialog.findViewById(R.id.btnCancel);
buttonCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
Just add a Context parameter to your SearchDialog() constructor.
Make it like this:
public SearchDialog(Context context){
//....
}
You could either define your own Interface and implement for every class, or make the main Activity method static (as long as it wont need to access anything in dynamic objects that aren't method arguments).
final class Uutil {
public void static func() {
}
}
then do it in your classes:
class A {
public void f() {
Uutil.func();
}
}