Cast Dialog to AlertDialog - android

I had the exact same code in antoher project, but it continues to crash here. I have implementation 'com.android.support:design:26.1.0' in my gradle. I'm really unsure of what the problem is. I've tried switching the gradle version, changing from v7 Dialog to the app Dialog. All fails regardless
java.lang.ClassCastException: android.app.Dialog cannot be cast to android.support.v7.app.AlertDialog
at com.example.weather.CreateCityDialog.onResume(CreateCityDialog.java:58)
import android.app.Dialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateCityDialog extends DialogFragment {
public interface NewCityHandler {
void onNewCityCreated(String cityName);
}
private NewCityHandler newCityHandler;
private EditText etName;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof NewCityHandler)
newCityHandler = (NewCityHandler) context;
else
throw new RuntimeException("Error");
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return super.onCreateDialog(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
final AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(etName.getText())) {
newCityHandler.onNewCityCreated(etName.getText().toString());
d.dismiss();
} else {
etName.setError("Empty field");
}
}
});
}
}
}

You have to return AlertDialog from onCreateDialog().
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}

Related

How to Add Go Back function in WebView inside Fragment ? (duplicate)

The current code is not working , I want to add goback feature in webview, when I press back button in mobile . How can I solve it? Below is my current fragment . Guide me :) found some question regarding same ,but didn't get the answer..
SOLVED! THIS IS WHAT I FOUND !!
///MY FRAGMENT
}
public static WebView getWebView(){
return webView;
}
}
----------------------
///MY ACTIVITY
#Override
public void onBackPressed() {
WebView webView = fbfragment.getWebView();
if (webView.canGoBack()) {
webView.goBack();
} else {
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}
}
package XXXX.XXXXXXXXXX.XXXXXXXXXXXX.com;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import XXXX.XXXXXX.XXXXXX..R;
import XXXX.XXXXXX.XXXXXX..R.id;
import XXXX.XXXXXX.XXXXXX.R.layout;
public class FBFragment extends Fragment {
private static final String target_url = "https://XXXXXXXXXX.com/";
private static WebView webView;
final Context context = getActivity();
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.XXXXX_main, container, false);
webView = (WebView) rootView.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
...........CONT...
.......CODE ENDS WITH..........
}
});
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
CookieSyncManager.getInstance().startSync();
webView.loadUrl(target_url);
return rootView;
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
}
public static boolean Back() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else
return false;
}
}
BELOW IS MY MAIN ACTIVITY
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}
Try below solutions
in your activity class's onBackPressed method call your fragment's Back() method.
#Override
public void onBackPressed()
{
yourFragment.Back();
}
in your fragment's Back() method call getActivity().onBackPressed(); like this
public static void Back() {
if (webView.canGoBack()) {
webView.goBack();
} else{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Exit").setMessage("Are you sure you want to exit?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
}
Override the onBackPressed() of your Activity
#Override
public void onBackPressed()
{
//fbFragment is an instance of your FBFragment
WebView webView = fbFragment.getWebView();
if (webView.canGoBack())
{
webView.goBack();
} else{
super.onBackPressed();
}
}
/// this is inside your fragment. NOTE the getWebview method
package XXXX.XXXXXXXXXX.XXXXXXXXXXXX.com;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import XXXX.XXXXXX.XXXXXX..R;
import XXXX.XXXXXX.XXXXXX..R.id;
import XXXX.XXXXXX.XXXXXX.R.layout;
public class FBFragment extends Fragment {
private static final String target_url = "https://XXXXXXXXXX.com/";
private static WebView webView;
final Context context = getActivity();
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.XXXXX_main, container, false);
webView = (WebView) rootView.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
...........CONT...
.......CODE ENDS WITH..........
}
});
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
CookieSyncManager.getInstance().startSync();
webView.loadUrl(target_url);
return rootView;
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
}
public void getWebView(){
return webview;
}

I want to display data from AlertDialog with an editText and then display it to a list view it'snot working, this is my code

package com.example.riplee07.trydialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listss = new ArrayList<String>();
ArrayAdapter <String>adapter;
String add1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText tt = (EditText)findViewById(R.id.editText);
final ListView lv = (ListView)findViewById(R.id.listView1);
Button br = (Button)findViewById(R.id.button);
add1 = tt.getText().toString();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listss);
lv.setAdapter(adapter);
listss.add(add1);
adapter.notifyDataSetChanged();
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listss.add(add1);
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
}
}
Try this code below (for getting edittext data):
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText et = (EditText) ss.findViewById(E.id.editText);
listss.add(et.getText().toString());
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
Here is the method in which i call on Button button.setOnClickListener
public void saveNote(View view){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_new_note_layout);
mTitle = (EditText)dialog.findViewById(R.id.titleID);
mMessage = (EditText)dialog.findViewById(R.id.messageID);
save = (Button)dialog.findViewById(R.id.saveBtn);
setFilePathll();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int titleLength = mTitle.getText().length();
if(titleLength != 0){
String title = mTitle.getText().toString();
String msg = mMessage.getText().toString();
helper.addNote(title, mFilePath, msg);
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this,"Empty Message is not valid",Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
Here helper.addNote(title, mFilePath, msg); is the method which i declared in the database helper class to insert data.
you Should use RecyclerView for what you want instead of using 'ListView'

Error in Alert dialog

There is an error in 'return view' at listview.setOnItemLongClickListener method. The error says cannot return a value from a method with void result type. I am trying to create an alert dialog where it will notify the user whether it wants to delete.
package com.example.user.swen;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.user.swen.DB.RecordsDataSource;
import com.example.user.swen.Model.Records;
public class Record extends ListActivity {
public Button NewButton;
public RecordsDataSource Recordsdatasource;
ArrayAdapter<Records> RecordAdapter;
List<Records> records;
ListView listview;
Records selectedRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Addrecords();
//Referencing the Database
Recordsdatasource = new RecordsDataSource(this);
Recordsdatasource.open();
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//set the listView to use the custom List Adapter
records = (List<Records>) Recordsdatasource.getAll();
RecordAdapter = new RecordAdapter(this, 0, (ArrayList<Records>) records);
listview = (ListView) findViewById(android.R.id.list);
listview.setAdapter(RecordAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Duty: " + selectedRecord.getType())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Information</font>"));
alert.show();
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(selectedRecord);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Alert!!</font>"));
alert.show();
return true;
}
});
return view;
}
public void Addrecords() {
NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecords = new Intent(Record.this, NewRecord.class);
startActivity(addrecords);
}
});
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
private void deleteItem(Records selectedRecord) {
Recordsdatasource.removeRecords(selectedRecord);
showToast(this, "Usage deleted");
RecordAdapter.notifyDataSetChanged();
RecordAdapter.notifyDataSetInvalidated();
refreshDisplay();
}
private void refreshDisplay() {
records = Recordsdatasource.getAll();
RecordAdapter.clear();
RecordAdapter.addAll(records);
}
}
You are trying to return a View from your Activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//...
return view;
}
As you can see, onCreate() in an Activity has a void return type, meaning you shouldn't be returning anything in this method.
From the looks of your code, you are attempting to use this layout as the Activity's layout, but you are confusing the View inflation code with that used in a Fragment's onCreateView() method, which does indeed require you to return a View.
In an Activity, you need to call setContentView() to set the layout. You can either set the layout using the resource ID via setContentView(R.layout.activity_record), or if you want to inflate the View yourself you can call setContentView(view).
The call return view is actually located in onCreate. The function onCreate is declared to return nothing (void). Therefore, you cannot return an instance of View. You just have to remove that line or replace it with return; Also, onItemLongClick must return a boolean. So you can't move return view there either.

Android : Evaluate Dialog

I want to evaluate a Dialog under Android.
My problem is that the Dialog does not wait
with returning a value until I pressed a
button. And when I use a Semaphore the
program hangs at Semaphore.acquire().
Why does it hang at Semaphore.acquire()?
Can you see where I go wrong?
Here is the main activity
package com.example.modaldialog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDialog meinDialog = new mDialog(this);
if (meinDialog.ShowMyModalDialog() == 1)
Toast.makeText(this, "Pressed Button 1",
Toast.LENGTH_LONG).show();
}
}
and here the dialog class
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
import java.util.concurrent.Semaphore;
import android.app.Activity;
import java.lang.Runnable;
public class mDialog
{
int pressedButtonID;
Activity act;
private final Semaphore dialogSemaphore;
mDialog(Activity act_in)
{
act = act_in;
dialogSemaphore = new Semaphore(0, true);
};
final Runnable mMyDialog = new Runnable()
{
public void run()
{
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogSemaphore.release();
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogSemaphore.release();
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
};
public int ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
act.runOnUiThread(mMyDialog);
try
{
dialogSemaphore.acquire();
}
catch (InterruptedException e)
{
}
return(pressedButtonID);
}
}
I am not much aware about the Semaphore but you can achieve the same with Interface. I have updated your code please find it below,
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class mDialog
{
int pressedButtonID=0;
private HandleDialogEvent dialogEvent;
mDialog(HandleDialogEvent dialogEvent)
{
this.dialogEvent = dialogEvent;
}
public void ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
public interface HandleDialogEvent{
public void getDialogId(int Id);
}
}

AlertDialog crashes application

Can someone explain to me why this AlertDialog crashes?
package com.clicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Clicker extends Activity
{
public int clickerNumber = 0;
private TextView clickerText;
private Button clickerButton;
private Button resetButton;
// Called when the activity is first created.
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare each of the layout objects
clickerText = (TextView)findViewById(R.id.clickerText);
clickerButton = (Button)findViewById(R.id.clickerButton);
resetButton = (Button)findViewById(R.id.resetButton);
clickerText.setText("0");
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
resetQuestion.setMessage("Are you sure you want to reset the counter?");
resetQuestion.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clickerNumber = 0;
clickerText.setText("0");
}
});
resetQuestion.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
clickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickerNumber++;
clickerText.setText(Integer.toString(clickerNumber));
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetQuestion.show();
}
});
};
};
This is a great fail:
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
You are trying to use a null object, and that (of course) will throw a NullPointerException
This is how I create dialogs (and I think it's the best way to do it):
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialogo_layout, null);
final AlertDialog.Builder resetQuestion = new AlertDialog.Builder(YourActivity.this)
// do whatever you want with the resetQuestion AlertDialog
Here, R.layout.dialogo_layout represent a file called dialogo_layout.xml in the res/layout dir that contains the dialog layout.

Categories

Resources