I would like to know how to put a Toast in each of these functions in the following lines:
Toast.makeText(OwnerAdapter.this,"Owner sucessfully deleted!",Toast.LENGTH_SHORT).show();
Toast.makeText(OwnerAdapter.this,"Owner updated successfully!",Toast.LENGTH_SHORT).show();
These functions are inside the OwnerAdapter class that serve to create a one-dimensional list of elements. But it's not working because the compiler throws an error:
Cannot resolved method 'makeText(com.example.iury.bookapp.OwnerAdapter,java.lang.String, int)
Code Here
public class Owner Adapter extends RecyclerView.Adapter<OnwerAdapter.ViewHolder> {
// Button update
holder.button_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_owner = holder.editName_owner.getText().toString();
String email_owner = holder.editEmail_owner.getText().toString();
String telephone_owner = holder.editTelephone_owner.getText().toString();
conexao.UpdateOwner(new Owner(f_owner.getId_owner(),name_onwer,email_owner,telephone_onwer));
notifyDataSetChanged();
Toast.makeText(OwnerAdapter.this,"Owner updated successfully!",Toast.LENGTH_SHORT).show();
((Activity) context).finish();
context.startActivity(((Activity) context).getIntent());
}
});
// Button delete
holder.button_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connection.DeleteOnwer(f_owner.getId_owner());
owner.remove(position);
Toast.makeText(OwnerAdapter.this,"Owner sucessfully deleted!",Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
}
You need to pass context to Toast to make it work.
If the adapter is inside an activity, you need to show a message like
Toast.makeText(getApplicationContext(),"Owner updated successfully!",Toast.LENGTH_SHORT);
If the adapter is inside a fragment, you need to show a message like
Toast.makeText(getActivity(),"Owner updated successfully!", Toast.LENGTH_SHORT).show();
If the adapter is written as a separate java file, you can do it like
Toast.makeText(v.getContext(),"Owner updated successfully!",Toast.LENGTH_SHORT).show();
or you could pass context to the adapter and pass that context to Toast
Toast.makeText(context,"Owner updated successfully!",Toast.LENGTH_SHORT).show();
Related
I am working on an app which would store data in Firebase. The issue is that when I click submit, the data stays on the form. I need when I click submit that it returns to the home screen.
I tried using the start activity method like I did when I wanted to move from MainActivity to another class. It would work but then my data will not be saved.
I am grateful for any assistance. Thanks in advance!
buttonSubmitReport.setOnClickListener(v -> {
reports.setDate(textDate.getText().toString().trim());
reports.setTime(textTime.getText().toString().trim());
reports.setReport(editRep.getText().toString().trim());
reff.push().setValue(reports);
reff.child(String.valueOf(maxID+1)).setValue("Reports");
Toast.makeText(submitReport.this,"Thanks for the information!", Toast.LENGTH_LONG).show();
}
});
What I am getting from your problem is that you have one activity from there you are starting another activity for editing the details and on click of some button, you want to save those details and come back to previous activity, right?
To do this just add some listener to that and when it completed simply finish the activity
buttonSubmitReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reports.setDate(textDate.getText().toString().trim());
reports.setTime(textTime.getText().toString().trim());
reports.setReport(editRep.getText().toString().trim());
reff.push().setValue(reports);
reff.child(String.valueOf(maxID + 1)).setValue("Reports")
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Write was successful!, here either finish or move to another activity
Toast.makeText(submitReport.this, "Thanks for the information!", Toast.LENGTH_LONG).show();
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Write failed
Toast.makeText(submitReport.this, "Failed to store the data", Toast.LENGTH_LONG).show();
}
});
});
You can use firebase value update listener, Once value update performs the operation.
Or you can use the firebase transaction handler.
override fun onComplete(dataBaseError: DatabaseError?, status: Boolean, snapShot: DataSnapshot?) {
//Operation complete call back
}
override fun doTransaction(data: MutableData): Transaction.Result {
//Perform your operation here
return Transaction.success(data)
}
})
You can try it once if possible
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
buttonSubmitReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertData();
ReportsID = Fetch Reports Id and use condition is empty or not
if (TextUtils.isEmpty(ReportsID)) {
InsertData();
} else {
//---Start Activity
}
}
});
}
public bool InsertData()
{
reports.setDate(textDate.getText().toString().trim());
reports.setTime(textTime.getText().toString().trim());
reports.setReport(editRep.getText().toString().trim());
reff.push().setValue(reports);
reff.child(String.valueOf(maxID+1)).setValue("Reports");
Toast.makeText(submitReport.this,"Thanks for the information!", Toast.LENGTH_LONG).show();
}
}
Don't know why this error is coming. I have used the same logic of adding #Override in my previous apps (Which I learned from Udacity).
I'm currently doing the Multiscreen Apps course. Do let me know if anyone else have completed this course or having the same error.
Here's what I wrote:
//Find the view that shows family category
TextView family = (TextView) findViewById(R.id.family);
//Send a clicklistner on that view
family.setOnClickListener(new View.OnClickListener()
{
#Override //here's the error
public void onClick (View v){
// create a new intent to open the {#link FamilyActivity}
Intent familyIntent = new Intent(MainActivity.this, FamilyActivity.class);
// start the new activity
startActivity(familyIntent);
}
});
Thanks,
Kvaibhav01.
Did you try this?
family.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
As I remember textView doesn't have onClickListener, it has onTouchListener and maybe this's a problem
Right now i'm having :-
1) 1 activity which is the main activity that extends from AppCompactActivity.
2) 1 fragment class that extends from fragment, this is the fragment that being called from main activity (1) - ProfileTeacherActivity.java
3) 1 fragment class that extends from DialogFragment, this dialog getting called from fragment (2) - ModalBox.java
So, basically, this is just a simple flow of execution. At start, the applications showing the main activity (1) having drawer that have a few links as example a profile link, when click this link, the application call the fragment (2) showing details of profile with one edit button. After clicking edit button, the applications will invoke DialogFragment (3) that contains some of EditText for editing user's profile.
What i want to achieve is, after editing user's profile and successful saved into database, i tried to send user's data back to fragment (2) just to show latest updated info, unfortunately it didn't work.
Here is what i'm tried :
1) Creating Interface inside DialogFragment (3) - ModalBox.java
public class ModalBox extends DialogFragment{
....
public interface EditProfileModalBoxInterface {
void onFinishEditProfile( HashMap<String, String> dataPassing );
}
...
...
}
2) Inside DialogFragment also i have .setPositiveButton function for OK button. - ModalBox.java
public class ModalBox extends DialogFragment{
...
...
public Dialog onCreateDialog(Bundle savedInstanceState ) {
...
builder
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int id) {
// At here i'm using retrofit2 http library
// to do updating stuff
// and inside success's callback of retrofit2(asynchronous)
// here i call the below function to send data
// dataToSend is a HashMap value
sendBackResultToParent( dataTosend );
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
.....
}
// Function called inside success's callback of retrofit2
public void sendBackResultToParent( HashMap<String, String> data ) {
// instantiated interface
EditProfileModalBoxInterface ls=(EditProfileModalBoxInterface)getTargetFragment();
// declaring interface's method
ls.onFinishEditProfile( data );
}
}
3) Finally, i'm implements those interface inside fragment (2) - ProfileTeacherActivity.java
public class ProfileTeacherActivity extends Fragment
implements ModalBox.EditProfileModalBoxInterface{
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState ) {
.....
.....
}
// At here the interface's method did't triggered
#Override
public void onFinishEditProfile( HashMap dataPassedFromDialog ) {
Toast.makeText(getActivity(), "Testing...." , Toast.LENGTH_LONG).show();
}
}
What i'm confuses right now is, the problem happens only when i called this function sendBackResultToParent( dataTosend ); inside retrofit2 success's callback, it does triggered when calling outside of it. I'm assumed the async called caused this. If i could use Promise or something like that or is there any workaround on this?
The following existing solutions didn't work in my case :
Callback to a Fragment from a DialogFragment
How to send data from DialogFragment to a Fragment?
Send Data from DialogFragment to Fragment
Ask me for more inputs if above use case didn't clear enough or misunderstanding. Thanks for the helps. Regards.
This is a sample DialogFragment code used to send message to selected contact. I too required to capture the click event on the DialogFragment and redirect.
Ideally to achieve this , this is what needed to be done
Override the positive/negative button clicks of AlertDialog.Builder and do no action
After this , using getButton method mention AlertDialog.BUTTON_NEGATIVE or AlertDialog.BUTTON_POSITIVE and assign an action
public class SMSDialogFrag extends DialogFragment {
private static String one="one";
private EditText messageContent;
private AlertDialog dialog;
private String mobNumber;
public static SMSDialogFrag showDialog(String mobNumber){
SMSDialogFrag customDialogFrag=new SMSDialogFrag();
Bundle bundle=new Bundle();
bundle.putString(one, mobNumber);
customDialogFrag.setArguments(bundle);
return customDialogFrag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.sms_dialog, null);
alertDialogBuilder.setView(view);
setupUI(view);
alertDialogBuilder.setTitle("");
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here because we override this button later
}
});
alertDialogBuilder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here because we override this button later
}
});
dialog = alertDialogBuilder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();//IN YOUR USE CASE YOU CAN REDIRECT TO YOUR CALLER FRAGMENT
}
});
return dialog;
}
void setupUI(View view){
TextView textViewMob=(TextView)view.findViewById(R.id.mobNumber);
messageContent=(EditText)view.findViewById(R.id.messageContent);
mobNumber=getArguments().getString(one);
textViewMob.setText("Send message to : "+mobNumber);
}
void sendMessage(){
if( ! TextUtils.isEmpty(messageContent.getText())){
try {
SmsManager smsManager = SmsManager.getDefault();
Log.v(Constants.UI_LOG,"Number >>>>>>> "+mobNumber);
smsManager.sendTextMessage(mobNumber, null, messageContent.getText().toString(), null, null);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getActivity(),"Message Sent!",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}else{
Toast.makeText(getActivity(),"Please enter message to send!",Toast.LENGTH_SHORT).show();
}
}
}
Consider using eventBus, for example
Otto
The usage is very simple. All you need to do is create an evenbus:
public static Bus bus = new Bus(ThreadEnforcer.MAIN); //use Dagger2 to avoid static
Then create a receiver method (in fragment 2 in your case):
#Subscribe
public void getMessage(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
Send you message by calling(from DialigFramgent):
bus.post("Hello");
And don't forget to register your eventBus inside onCreate method(of your Fragment):
bus.register(this);
And that is!
From architectural standpoint, 2 fragments should not directly communicate with one another. Container Activity should be responsible for passing data between it's child fragments. So here's how i would do it:
Implement your interface in the container Activity and just attach your interface implementation in the Activity to the Dialog class and call that interface method when required. Something like this :
public static class ModalBox extends DialogFragment {
EditProfileModalBoxInterface mListener;
// Container Activity must implement this interface
public interface EditProfileModalBoxInterface {
void onFinishEditProfile( HashMap<String, String> dataPassing );
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (EditProfileModalBoxInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement EditProfileModalBoxInterface");
}
}
}
Then call mListener.onFinishEditProfile(....) where ever it's required in the DialogFragment class.
This way you will receive the result back in your Activity class from where you can call your desired fragment's relevant method to pass the results to that fragment.
This whole flow has been described here
Finally the culprit founds. All the answers mentioned above were right. And my script also actually works, the problem is related with my API json's response that did't coming with right structure. In my case, i'm using retrofit2 with GSON converter for parsing into POJO. Found the info on log saying about :
Expected BEGIN_OBJECT but was BEGIN_ARRAY
Means that, GSON expecting the json object, which is my API was returned JSON array. Just change the API's structure then all goods to go. Thanks guys for your hard time. Really appreciated, as i'm right now knowing how to deal with eventBus, replacing default OK and Cancel button and the correct way for communicating between fragments.
In my app after they press an on screen button. In the listener I do some check to see if they win. When they win i set a boolean like so:
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
}
}
I am wondering. Where does the code go after the onClick. Am i suppose to call the function in the onClick?
I have looked everywhere for an answer, I am very new to android programming.
If by "the function" you mean a funcion that you have developed, then Yes, you should call whatever function you want to execute in the onClick method.
For example:
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
//Example
this.informUser(aWin) //Call your function here
}
}
If by "the funcion" you mean the onClick, then no, you shouldn't call it, Android OS should do it for you.
Where does the code go after the onClick. Am i suppose to call the
function in the onClick?
It depends on what you do in the onClick.
For example :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
}
}
In your code above, the code will stop at aWin = true;.
Now lets say you want to go to another Activity after a click happened :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
Intent i = new Intent(this, AnotherActivity.class);
startActivity(i);
}
}
The onClick will end when your apps go to another activity.
UPDATE
Lets say you want to "refresh" your TextView after a click happened :
button.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
/** check some things **/
aWin = true;
if(aWin)
myText.setText("WIN");
else
myText.setText("LOSE");
}
}
Feel free to comment if you still have some questions (although no guarantee i can answer it) :)
Im brand new to android and I have no idea what I'm doing wrong. The current code looks like:
public class TypeActivity extends Activity {
private boolean alcoholin = false;
...
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search_type);
alcohol = (Button) findViewById(R.id.alcohol_button);
...
alcohol.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alcoholin=true;
Intent i = new Intent (TypeActivity.this,ingredients.class);
startActivity(i);
}
});
...
public boolean getalcholin(){
return alcoholin;
}
This code is then supposed to set a value in another class. I have tested the code and I know that if i state the the boolean is true in the beginning of my code, then I will make the other code's boolean equal true. However, if I try to set the value when the user presses the button the value does not get updated.
Please help!
On Android the standard way to send data from one Activity to another is by specifying "extras" on the Intent that you use to start a new activity.
You are already using an Intent in your onClick method to start your "ingredients" activity (Your code would be more readable if you named your activity something like IngredientsActivity instead) - you just need to add some "extras" to it.
Please read up on the training tutorial here, but without knowing what your ultimate goal is you probably want something like:
alcohol.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent (TypeActivity.this,IngredientsActivity.class);
i.putExtra(IngredientsActivity.EXTRA_INGREDIENT_TYPE, "alcohol");
startActivity(i);
}
});
... and then in IngredientsActivity you would have something like:
public static final String EXTRA_INGREDIENT_TYPE = "ingredient";
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredients);
String ingredientType = getIntent().getStringExtra(IngredientsActivity.EXTRA_INGREDIENT_TYPE);
}
This would never work because alcoholin would NOT exist as this is an entirely different Activity. Why don't you instead use the Extras of the intent to pass data between the two Activities.
Standards
Class names should always have each word capitalized like MyClassObject in java.