Passing data from an adapter over a dialog to a activity - android

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

Related

Dialog pops up very slow

In my app I have implemented this custom dialog (which has a fairly complex layout) by extending DialogFragment. I expect this dialog to pop up when I click a button in my layout. (Which I have successfully achieved). But the problem is that the dialog shows up in a janky manner.
My custom dialog class:
public class CustomizeDialog extends DialogFragment implements AdapterView.OnItemSelectedListener {
// field declarations go here
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.customize_dialog, null);
builder.setView(view)
.setTitle("Customize")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Let's go!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction("fromDialog");
intent.putExtra("ratio",getRatio(paperSizeSpinner.getSelectedItem().toString()));
if(isOrientationSpinnerVisible){
intent.putExtra("isCustom",false);
intent.putExtra("orientation",orientationSpinner.getSelectedItem().toString());
} else {
intent.putExtra("isCustom",true);
}
intentProvider.getIntent(intent);
}
});
widthEditText = view.findViewById(R.id.width_et);
heightEditText = view.findViewById(R.id.height_et);
widthEditText.setEnabled(false);
heightEditText.setEnabled(false);
paperSizeSpinner = view.findViewById(R.id.paper_size_spinner);
orientationSpinner = view.findViewById(R.id.orientation_spinner);
// ArrayList for populating paperSize spinner via paperSizeAdapter
ArrayList<String> paperSizes = new ArrayList<>();
paperSizes.add("A0");
paperSizes.add("A1");
paperSizes.add("A2");
paperSizes.add("A3");
paperSizes.add("A4");
paperSizes.add("A5");
paperSizes.add("Custom");
// ArrayList for populating orientation spinner via orientationAdapter
ArrayList<String> orientation = new ArrayList<>();
orientation.add("Portrait");
orientation.add("Landscape");
// arrayAdapters containing arraylists to populate spinners
ArrayAdapter paperSizeAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_dropdown_item, paperSizes);
ArrayAdapter orientationAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_dropdown_item, orientation);
paperSizeSpinner.setAdapter(paperSizeAdapter);
orientationSpinner.setAdapter(orientationAdapter);
paperSizeSpinner.setSelection(4);
paperSizeSpinner.setOnItemSelectedListener(this);
orientationSpinner.setOnItemSelectedListener(this);
return builder.create();
}
// These are some important complex ui functionalities
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.paper_size_spinner) {
if (position == 6) {
widthEditText.setEnabled(true);
heightEditText.setEnabled(true);
orientationSpinner.setEnabled(false);
isOrientationSpinnerVisible = false;
} else {
widthEditText.setEnabled(false);
heightEditText.setEnabled(false);
orientationSpinner.setEnabled(true);
isOrientationSpinnerVisible = true;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
// interface used to communicate with the parent activity
public interface IntentProvider {
// this method is used to provide the intent to the parent activity
void getIntent(Intent intent);
}
// instantiating the interface object and throwing error if parent activity does not implement this interface
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
intentProvider = (IntentProvider) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement IntentProvider");
}
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity implements CustomizeDialog.IntentProvider {
// field declarations go here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image);
// instantiating the dialog
final CustomizeDialog dialog = new CustomizeDialog();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// showing the dialog on click
dialog.show(getSupportFragmentManager(),"");
}
});
}
// via this method I receive the intent from the dialog
// I know intent might not be the best option for this function but let's let it be here for now
#Override
public void getIntent(Intent intent) {
ratio = intent.getFloatExtra("ratio",3);
isCustom = intent.getBooleanExtra("isCustom",false);
orientation = intent.getStringExtra("orientation");
launchChooser();
}
}
Let me know in the comments if you want the layout code for the dialog.
What I tried:
Implementing threading so that my dialog is ready in a background thread and show it onButtonClick. But this is not allowed in general as any other thread except UI thread aren't supposed to touch UI related events.
Using onCreateView instead of onCreateDialog to inflate the layout directly.
Making the dialog a global variable, initialized it in onCreate and then show the dialog onButtonClick.
Switched to CONSTRAINT LAYOUT
Using an activity as a dialog by setting the dialog theme to the activity in the manifest file.
Launched my app in a device with better hardware than mine.
BUT NOTHING WORKED
What I want:
Why is my dialog janky? and what I need to do to make the dialog pop up faster?
In case anybody wants here's the link to my app repo on github.
AlertDialog and DialogFragment frameworks are slow because they need to some time to do calculations and fragment stuffs. So a solution to this problem is, using the Dialog framework straight away.
Use the Dialog framework's constructor to initialize a Dialog object like this:
Dialog dialog = new Dialog(context, R.style.Theme_AppCompat_Dialog);
// the second parameter is not compulsory and you can use other themes as well
Define the layout and then use dialog.setContentView(R.layout.name_of_layout).
Use dialog.findViewById(R.id.name_of_view) to reference views from the dialog's layout file
And then implement the logic just like anyone would do in an activity class. Find out the best implementation for your use case by reading the official documentation.

How to avoid Null Pointer Exception in Two Activities Communication

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;
}

Update RecyclerView from Dialog

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();
}

Activity as dialog from BroadcastReceiver over another activity

My app listens for an Intent fired by a third party app when an Activity in that app is shown. The Intent is received in a BroadcastReceiver in my app. I want to start an Activity from the BroadcastReceiver which will show as a Dialog over the existing activity (that fired the Intent).
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, ">>>>>>>>> Action:" + action);
if ("clover.intent.action.V1_ORDER_BUILD_START".equals(action)) {
Intent i = new Intent(context.getApplicationContext(), ActiveOrderActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
The Intent clover.intent.action.V1_ORDER_BUILD_START is fired by a different app which my app listens for. When this Intent is fired, an Activity is already open (see the background activity in the picture below).
Now I want to show an Activity in my app as Dialog over the already shown activity, just like the "Add Customer to Order" in the image below.
As shown in the code above, I am starting an Activity from BroadcastReceiver, but when it starts, it comes to foreground and the previous Activity is not shown.
See below for an example of what I want to achieve,
Maybe you should create
public class MyDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflaterViewObject = LayoutInflater.from(getActivity());
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View DialogView = inflaterViewObject.inflate(R.layout.dialog, null);
final AlertDialog Dialog = new AlertDialog.Builder(getActivity()).create();
Dialog.setView(DialogView);
DialogView.findViewById(R.id.dialog_YES).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your YES logic
Dialog.dismiss();
}
});
DialogView.findViewById(R.id.dialog_NO).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your NO LOGIC
Dialog.dismiss();
}
});
// return dialog object (later on .show());
return Dialog;
}
Later you write in your choosen place (in BrodcastReciever)
MyDialog dialogObject = new MyDialog();
dialogObject.show(getFragmentManager(), "tag name for the dialog fragment.");

Trying to use getIntent() within a custom dialog comes up as an error. Solution to get around this error?

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...)

Categories

Resources