I'm trying to call a method that is inside another class that will populate TextViews when an item is clicked inside AutoCompleteTextView that is also inside an AlertDialogInput.
But my app crashes when I click an Item.
I'm new in android development so any help would be pretty much appreciated.
Custom Alert Dialog
Alert Dialog Class
public static class ToPrintAccountSearchDialog extends AppCompatDialogFragment
{
private AutoCompleteTextView toprint_auto_account_search_dialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.for_printing_account_search_dialog_layout, null);
builder.setView(view);
builder.setTitle("Search Account");
List<ForBillPrintConsumerEntities> forBillPrintConsumerEntities = new ArrayList<>();
toprint_auto_account_search_dialog = view.findViewById(R.id.Alert_Dialog_Account_Auto_Search);
ForPrintingConsumerAccountSearchAdapter forPrintingConsumerAccountSearchAdapter = new ForPrintingConsumerAccountSearchAdapter(getActivity(), forBillPrintConsumerEntities);
toprint_auto_account_search_dialog.setThreshold(1);
toprint_auto_account_search_dialog.setAdapter(forPrintingConsumerAccountSearchAdapter);
toprint_auto_account_search_dialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
PrintBill printBill = new PrintBill();
printBill.getotherinformationbyaccountforprinting();
}
});
return builder.create();
}
}
This is the code to show AlertDialogInput
Main Activity
Account_No = findViewById(R.id.toprint_Account_No_Value);
Account_No.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
forPrintAccountSearchDialog();
}
});
public void forPrintAccountSearchDialog()
{
ToPrintAccountSearchDialog toPrintAccountSearchDialog = new ToPrintAccountSearchDialog();
toPrintAccountSearchDialog.show(getSupportFragmentManager(), "ToPrintAccountSearchDialog");
}
this is the method that I want to call when an Item is clicked inside AlertDialog AutocompleteTextview that is also inside Main Activity to populate my textview insid main activity
public void getotherinformationbyaccountforprinting()
{
ConsumerAccountForPrinting = toprint_auto_account_search_dialog.getText().toString();
db = new DatabaseHelper(getApplicationContext());
sqLiteDatabase = db.getReadableDatabase();
Cursor cursor = db.ForPrintingGetOtherInfoByAccount(ConsumerAccountForPrinting, sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String ACCOUNT_NUMBER = cursor.getString(0);
String NAME = cursor.getString(1);
String ADDRESS = cursor.getString(2);
Account_No.setText(ACCOUNT_NUMBER);
Name.setText(NAME);
Address.setText(ADDRESS);
}
while (cursor.moveToNext());
}
}
Data Base Helper
public Cursor ForPrintingGetOtherInfoByAccount(String keyword, SQLiteDatabase sqLiteDatabase)
{
String [] projections = {ForPrintingConsumerOtherInfoAdapterByAccount.getOtherInfoForPrintingByAccount.ACCOUNT_NO,
ForPrintingConsumerOtherInfoAdapterByAccount.getOtherInfoForPrintingByAccount.NAME,
ForPrintingConsumerOtherInfoAdapterByAccount.getOtherInfoForPrintingByAccount.ADDRESS,
String selection = ConsumerListOtherInfoAdapterByAccount.getOtherInfoForListByAccount.CONSUMER_ACCOUNT_NO+" LIKE ?";
String [] selection_args = {keyword};
Cursor cursor = sqLiteDatabase.query(ForPrintingConsumerOtherInfoAdapterByAccount.getOtherInfoForPrintingByAccount.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}
projection that calls inside database helper
public class ForPrintingConsumerOtherInfoAdapterByAccount
{
public static abstract class getOtherInfoForPrintingByAccount
{
public static final String TABLE_NAME = "toPrintBill";
public static final String ACCOUNT_NO = "account_no";
public static final String NAME = "name";
public static final String ADDRESS = "address";
}
}
When I Click The Text View Alert Dialog Pops Up
When I Type number The autocompletetextview will suggest data that has the same value from sqlite database table
But when I click an Item this Happens
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.AutoCompleteTextView.getText()' on a null object reference
at com.vicjames.qiimeterreader.PrintBill.getotherinformationbyaccountforprinting(PrintBill.java:224)
at com.vicjames.qiimeterreader.PrintBill$ToPrintAccountSearchDialog$1.onItemClick(PrintBill.java:189)
at android.widget.AutoCompleteTextView.performCompletion(AutoCompleteTextView.java:1017)
How can I create communication between my alert dialog class and main activity so i can use that method?
Use LocalBroadcastManager. Register a receiver in onResume method in your activity, with a specific action, for example "executeMainActivityCode" can be it. For that, you need something like this:
onResume:
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("executeMainActivityCode"));
onPause (don't forget about this):
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver));
From your dialog, call this code:
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent("executeMainActivityCode"));
Inside the receiver, call your method in onReceive and you're good to go.
You're calling findViewById too early:
Account_No = findViewById(R.id.toprint_Account_No_Value);
This calls it when the Activity is being constructed. Try replacing Account_No in getotherinformationbyaccountforprinting with findViewById(R.id.toprint_Account_No_Value), or setting up Account_No in onCreate after calling setContentView.
As I suggested in the comment you can use interface to communicate between Activities/Fragments/Adapters/etc`.
1. create an Interface
public interface DataTransfer{
void sendData(String data); //change parameter to whatever you want
}
2. implement the interface in your activity
3. pass interface in alertDialog
ToPrintAccountSearchDialog toPrintAccountSearchDialog =
new ToPrintAccountSearchDialog(this);
// here this will pass the implemented interface
4. in your dialog receive the interface using constructor
private DataTransfer dataTransfer;
public ToPrintAccountSearchDialog(DataTransfer dataTransfer){
this.dataTransfer = dataTransfer;
}
5. User this dataTransfer to pass data to activity
dataTransfer.sendData("Some important data");
6. In your activity there will be an #Override method void sendData(String data);
#Override
public void sendData(String data) {
Log.e("TAG", "sendData: this data is from Dialog " + data);
}
Edit 1: explanation
There is 1 Activity A and 1 DialogFragment B
B wants to send data to A
A gives B an interface so when B calls dataTransfer.sendData("Hello");
A will also call it's own overridden sendData(String data);
Now if you print this
#Override
public void sendData(String data) {
Log.e("TAG", "sendData: " + data);
}
This will print
Hello
You can call any other method from sendData
Hope this will help!
Please ask if you need more help
Found an answer on how to get the text from AutoCompletetextview from another class or a fragment
Inside Main Activity on Create Add fragment support
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ToPrintAccountSearchDialog toPrintAccountSearchDialog = new
ToPrintAccountSearchDialog();
ToPrintNameSearchDialog toPrintNameSearchDialog = new ToPrintNameSearchDialog();
fragmentTransaction.add(R.id.activity_print_bill,toPrintAccountSearchDialog);
fragmentTransaction.commit();
Then Inside your fragment onCreate Add the following codes
toprint_auto_account_search_dialog =
view.findViewById(R.id.Alert_Dialog_Account_Auto_Search);
toprint_auto_account_search_dialog.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String account_no_to_print =
toprint_auto_account_search_dialog.getText().toString();
PrintBill printBill = (PrintBill) getActivity();
printBill.account_no_to_print(account_no_to_print);
dismiss();
}
Then Inside Main Activity Create a variable and put the value of autocompletetextview like this
public void account_no_to_print(String account_no)
{
this.ConsumerAccountForPrinting = account_no;
}
Related
I am attempting to pass data from my adapter to an activity with a dialog between them.
My current data flow is
RecyclerAdapter --> Confirmation Activity --> Chat Activity
What I want
RecyclerAdapter --> Custom Dialog --> Chat Activity
previously in my on click, I just had an intent to carry it over to the confirmation activity then to the chat activity but I am unable to do that now. I read on this post about using shared preferences but was unable to successfully implement it so I am wondering if there is a better way to go about it if i am missing any information pleas let me know and i will update it
adapter
public void openDialog(){
FragmentManager manager = ((AppCompatActivity)mContext).getSupportFragmentManager();
Confirmation_Dialog confirmation_dialog = new Confirmation_Dialog();
confirmation_dialog.show(manager, "example dialog");
}
dialog
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Are You Sure");
mYesBtn = view.findViewById(R.id.yes_button_dialog);
mNoBtn = view.findViewById(R.id.no_button_dialog);
mYesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "it worked YES!!", Toast.LENGTH_SHORT).show();
}
});
mNoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
}
Just use bundle to pass data to the new Activity.
In the adapter
String value="Hello world";
Intent i = new Intent(context, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Your dialog is FragmentDialog, you can use setArguments method to pass argument.
Don't use shared pref to pass data, shared pref is more like saving data in the phone for future reference. In this case (like #average_developer suggested) use Intent Bundles to pass data to the targeted activity.
I think in your case, you have to use (code below) to actually get some information to identify which chat it will be created in the following activity.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
Intent i = new Intent(this, ProductActivity.class);
i.putExtra("item_id", manager.getItemIdAtIndex(pos));
startActivity(i);
}
You can create adapter click event in to activity class and make interface in to your adapter like below in your adapter do like:
onCircularsClick _oncircularClick;
public interface onCircularsClick {
public void _onCircularClick(Circular.TableBean bean);
}
your adapter constructor
public CircularListAdapter(Context ctx, onCircularsClick __oncircularClick) {
this.ctx = ctx;
this._oncircularClick = __oncircularClick;
}
and set click like
viewHolder.lin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
_oncircularClick._onCircularClick(list.get(i));//data that you want to pass when click fires
}
});
and while setting adapter from your activity you can get this click event over there so can write code for click (open dialog ) in to activity class
Instead of having the dialog in a separate file I just moved it into the adapter class
how to update recyclerview from a dialog which is in another class?
My dialog is as a separate class which is called from mainActivity. When I do changes in database, I would like to update recyclerview, which is on mainActivity.
Dialog:
public class Dialog {
DatabaseExecutor databaseExecutor = new DatabaseExecutor();
private final Activity activity;
private final List<Passenger> passengers;
private final int position;
public Dialog (final Activity activity, final List<Passenger> passengers, final int position){
this.activity = activity;
this.passengers = passengers;
this.position = position;
}
public void showDialog (){
final BottomSheetDialog dialog = new BottomSheetDialog(activity);
dialog.setContentView(R.layout.custom_dialog);
final AppCompatImageView dial, message, info, paid, edit, delete;
final AppCompatTextView name;
name = dialog.findViewById(R.id.dialog_name);
paid = dialog.findViewById(R.id.dialog_paid);
name.setText(passengers.get(position).getName());
if(passengers.get(position).isPaid())
paid.setImageResource(R.drawable.money_paid_72);
else
paid.setImageResource(R.drawable.money_unpaid_72);
paid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Passenger passenger = passengers.get(position);
if (!passengers.get(position).isPaid()){
passenger.setPaid(true);
passenger.setTumblr(R.drawable.money_paid);
passenger.setUser(R.drawable.user_icon);
paid.setImageResource(R.drawable.money_paid_72);
}
else {
passenger.setPaid(false);
passenger.setTumblr(R.drawable.money_unpaid);
passenger.setUser(R.drawable.user_icon_unpaid);
paid.setImageResource(R.drawable.money_unpaid_72);
}
databaseExecutor.updatePassenger(activity, passenger);
}
});
dialog.show();
}
}
P.s. when this dialog was in mainActivity, I just called populateData method and it worked. But how to refresh it from this Dialog class?
You can use callback with dialog in MainActivity,
public interface DialogCallback {
public void onDialogCallback();
}
Your Dialog constructor should be,
DialogCallback callback;
public Dialog (final Activity activity, final List<Passenger> passengers, final int position, DialogCallback callback){
this.activity = activity;
this.passengers = passengers;
this.position = position;
this.callback = callback;
}
In your Dialog button click use below code,
paid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Passenger passenger = passengers.get(position);
if (!passengers.get(position).isPaid()){
passenger.setPaid(true);
passenger.setTumblr(R.drawable.money_paid);
passenger.setUser(R.drawable.user_icon);
paid.setImageResource(R.drawable.money_paid_72);
}
else {
passenger.setPaid(false);
passenger.setTumblr(R.drawable.money_unpaid);
passenger.setUser(R.drawable.user_icon_unpaid);
paid.setImageResource(R.drawable.money_unpaid_72);
}
databaseExecutor.updatePassenger(activity, passenger);
callback.onDialogCallback(); // Add this line
}
});
In your MainActivity use below code,
Dialog dialog = new Dialog(this, passengers, position, new DialogCallback() {
#Override
public void onDialogCallback() {
// Update recycler view code here
}
});
dialog.showDialog();
In Dialog :
Have an interface
public interface onDialogFinishCallback
{
void refreshRecyclerView();
}
Now implement the above in your activity.
before dismiss the dialog or after the db change operation call
callback.refreshRecyclerView
A direct solution would be to call method on activity you passed to the dialog. There refresh data of recyclerview and notifyDataSetChanged() or appropriate.
A more general and imo better, architecture-related solution is to use Room or similar db, where you can observe data for changes. Let's say data in the db is changed anywhere. All the places where this data is observed (like with LiveData), data is refreshed. If you also use Paging library, data is refreshed and animated in recyclerview too.
Dialog shouldn't refresh RecyclverView directly. Instead you should pass listener from activity. Activity can refresh recycler if needed with notifyDataSetChanged.
Usually dialog should be 'dumb' ui and you shouldn't give it too much control, especially not over elements that are not shown inside dialog. Such approach will make your dialogs more reusable and easy to maintain.
Write an interface in your dialog
public interface onClickInterface{
public void updateRecyclerView(int position);
}
declare new variable for this interface in your dialog class
private onClickInterface mOnClickInterface;
then call method updateRecyclerView() from dialog class where you want to update recyclerview
mOnClickInterface.updateRecyclerView(position);
then implement your MainActivity for this interface and override this method
#override
public void updateRecyclerView(int position){
//alter your list which you are passing to your adapter
Passenger passenger = passengers.get(position);
passenger.setPaid(true);
rAdapter.notifyDatasetChanged();
}
Here there is minor issue Like I had Recyclerview in dialog fragment.ie name of bank in recyclerview When we select one bank in recyclerview and after dialogfragment dismiss that name should be appear on Button ie when we selected Union Bank from dialog fragment it should appear on button.Issue is when we click on button then its text changes rather then on time of dismiss listener
here is Dialog dismissal code:
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getContext(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, final int position) {
Employee e = bank.get(position);
Toast.makeText(getContext(), e.getBank_id() + "" + e.getBank_name(), Toast.LENGTH_SHORT).show();
getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
Employee e = bank.get(position);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor edit = sp.edit();
edit.putString("bankname", e.getBank_name());
edit.commit();
}
});
c.onItemSelect(e.getBank_name());
onDismiss(getDialog());
}
Here is onclick event where dialog opens and where the value should be printed:
select_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm=getFragmentManager();
DialogRecyclerview dr = new DialogRecyclerview(AccountManagement_banks.this,callback);
dr.setRetainInstance(true);
dr.show(getSupportFragmentManager(), "Dialog");
SharedPreferences st = PreferenceManager.getDefaultSharedPreferences(AccountManagement_banks.this);
String mode=st.getString("bankname","");
select_button.setText(mode);
Toast.makeText(getApplication(),mode,Toast.LENGTH_SHORT).show();
}
});
Same in:
#Override
public void onItemSelect(String text) {
select_button.setText(text);
}
Here I had created new Interface:
public interface CallBack {
void onItemSelect(String text);}
just create a callback and implement it on your main class (where you want to display the name) and pass the callback instance to adapter. Now dialog fragment, now when you are selecting any item just call callback function which is overridden in main calss and inside this function just change the text of your button.
public interface CallBack {
void onItemSelect(String text);
}
implement this in your main class like
public class MainActivity extends Activity implements CallBack {
.
.
.
public void onItemSelect(String text){
button.setText(text);
}
.
.
}
when you are opening your dialogfragment from your main activity just pass MainActivity.this as an argument in the dialog constructor. And in your Dialog class constructor write your code like this
private Callback callback;
public YourDialog(Context context, Callback callback){
this.callback = callback;
}
and when you selecting list item just call
callback.onItemSelect(e.getBank_name());
Hope it will help you out.
I have a problem to call a function of my Activity out of DialogFragment. There are public functions in my MainActivity which I need to call for some calculations that are done in the DialogFragment. Everytime I try to call a function with getActivity(). there occurs the problem "Cannot resolve method".
Here is how I call the DialogFragment in the MainActivity:
FragmentManager fm = getSupportFragmentManager();
DialogWeekly dialogWeekly = new DialogWeekly();
dialogWeekly.show(getFragmentManager(), "fragment_dialogWeekly");
And this is how the DialogFragment looks like. I have added two comment lines where the mentioned problem occurs:
public class DialogReminder extends DialogFragment implements AdapterView.OnItemSelectedListener {
//--- Static Variables -----------------------------------------------------------------------//
private static final String MY_PREFS = "my_preferences";
private static Activity activity;
private static TimePicker timePicker;
private static View dialogReminderView;
//--- Integer Variables ----------------------------------------------------------------------//
private Integer weekday;
//--- String Variables -----------------------------------------------------------------------//
private String weekdayString;
//--- Other Variables ------------------------------------------------------------------------//
private SharedPreferences sharedPreferences;
/**
* Empty constructor required for DialogFragment
*/
public DialogReminder() { }
/**
* Called when a fragment is first attached to its activity.
* onCreate(Bundle) will be called after this
* #param activity Activity that is attached to this fragment
*/
public void onAttach(Activity activity) {
super.onAttach(activity);
}
//--- Override Functions ---------------------------------------------------------------------//
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_weekly, container);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
return createAlertDialog();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Integer selectedItem = parent.getSelectedItemPosition();
weekdayString = parent.getItemAtPosition(pos).toString();
// Here is the problem: savePreferences -> cannot resolve method
getActivity().savePreferences("spinnerSelectionWeekday", String.valueOf(selectedItem));
weekday = selectedItem + 2;
if (weekday == 8) {
weekday = 1;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
//--- General Activity Functions -------------------------------------------------------------//
/**
*
* #return
*/
private AlertDialog createAlertDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(getResources().getString(R.string.optionReminder));
alert.setView(dialogReminderView);
alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setReminder();
dialog.cancel();
}
});
setElementsGUI();
return alert.create();
}
/**
*
*/
private void setElementsGUI() {
Spinner spinner = (Spinner) dialogReminderView.findViewById(R.id.reminderWeekdaySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.reminderSpinnerArray, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(this);
spinner.setAdapter(adapter);
spinner.setSelection(Integer.parseInt(sharedPreferences.getString("spinnerSelectionWeekday", "0")));
}
//--- Button Functions -----------------------------------------------------------------------//
/**
*
*/
private void setReminder() {
// Here is the problem: all functions with getActivity() -> cannot resolve method
getActivity().checkReminder();
getActivity().setWeekdayReminder(weekday);
getActivity(("hour", String.valueOf(timePicker.getCurrentHour()));
getActivity().savePreferences("minute", String.valueOf(timePicker.getCurrentMinute()));
getActivity().checkReminder();
String hour = String.valueOf(getActivity().getHour());
if (hour.length() < 2) {
hour = "0" + hour;
}
String minute = String.valueOf(getActivity().getMinute());
if (minute.length() < 2) {
minute = "0" + minute;
}
String time = hour + ":" + minute;
String message = getResources().getString(R.string.reminderToast, weekdayString, time);
Toast toast = Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_LONG);
toast.show();
}
}
While getActivity() returns a MainActivity at runtime, the compiler has to assume that it's just an Activity object and that those methods don't exist (since an Activity has none of these methods). Hence the compiler error.
What you need to do is cast the Activity to a MainActivity object like so:
((MainActivity)getActivity()).savePreferences(...
In kotlin we can cast the Fragment to a MainActivity object like this
(activity as MainActivity).yourMethodeName()
I am sending a string from an activity to my custom dialog.
This is the activity in which I create a bundle and insert the string, then send it to the dialog activity.
Bundle sendToDialog = new Bundle();
sendToDialog.putString("caloreis", strCalories);
Intent a = new Intent(CaloriesLogMainActivity.this, ActivityDialog.class);
a.putExtras(sendToDialog);
This is the custom dialog activity in which I am trying to receive the intent from the activity.
getIntent(), is coming up as an error. How would I get around this error?
public class ActivityDialog {
Context mContext;
Date mDate;
public ActivityDialog(Context context, CaloriesLogMainActivity caloriesLogMainActivity) {
mContext = context;
}
public void show() {
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
you have to extend Activity class , then only you can access getIntent()...
so your code should be like this
public class ActivityDialog extends Activity{
Context mContext;
Date mDate;
protected void onCreate(Bundle savedInstanceState){
//here you can call getIntent()
}
public void show() {
// or even from here ,you can call getIntent()
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
Your ActivityDialog class is an Activity and thus should extend Activity. This is a general rule, but specifically your problem here is due to the fact that getIntent() is defined in Activity, so you must extend that in order to use it.
It might be because of your spelling mistake in sendToDialog.putString("caloreis", strCalories); because you later reference the extra as "calories" not "caloreis". (I tried to put this in an edit but it was uner 6 characters long...)