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();
}
}
Related
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();
I have a function that requests data from an api and fills an array list.
Then i use the data from the arraylist in a textView. The problem that occurs is that the function takes time to load the data and the code in which i set the text view gets executed before the arraylist is populated resulting in a crash...I have used Countdown latch to tackle this problem but it isnt working
i have used it wrong most probably.
apirequest function
private void RequestDataFromApi() {
DotaAPIEndpoints textApiService= API_Client.getClient().create(DotaAPIEndpoints.class);
Call<List<Heroes>> call2 =textApiService.getHeroes();
call2.enqueue(new Callback<List<Heroes>>() {
#Override
public void onResponse(Call<List<Heroes>> call, Response<List<Heroes>> response) {
hero_list.clear();
hero_list.addAll(response.body());
}
#Override
public void onFailure(Call<List<Heroes>> call, Throwable t) {
Toast.makeText(MainActivity.this, "hero_list call failed!", Toast.LENGTH_SHORT).show();
}
});
requestLatch.countDown();
}
setText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
requestLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
textt.setText(hero_list.get(0).getHeroImg());
}
});
setText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
requestLatch.await();
You cannot call await on the UI thread. Calling await at this point in the above code is telling the UI thread to wait - if the UI thread is waiting, it cannot draw the screen updates, so the system will crash with an Activity Not Responding error.
Perhaps this helps, this is a way to safely allow the button to be clicked and not crash if the data has not loaded yet. (No need for a CountdownLatch at all)
setText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hero_list.isEmpty()) {
Toast.makeText(MainActivity.this, "List not ready", Toast.LENGTH_SHORT).show();
return;
}
textt.setText(hero_list.get(0).getHeroImg());
}
});
Hi i have created a class that extends HostApduService and there is a scenario where i want to stop or pause the service awaiting some input from the user before resuming the service again. Is this possible?
i could not find any API that manually stops/pauses the HostApduService.
snippet of my HostApduService on what i want it to do
protected byte[] processApdu(byte[] apdu) {
if(isEnabled){
/proccess apdu as normal
}
}
snippet of some action in android on a ui
new View.OnClickListener() {
#Override
public void onClick(View v) {
//disable/pause hostapdu service???
}
});
new View.OnClickListener() {
#Override
public void onClick(View v) {
//enable/resume hostapdu service???
}
});
processApdu always needs to return some bytes to the terminal but i dont want it to and want to disablle/pause it until further notice
To disable:
context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, MyHostApduService.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
To enable:
context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, MyHostApduService.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)
You could also try saving the enabled/disabled state in Shared Preferences
I am doing an HTTP request from my InitActivity:
private void initUserById(int challengerId) {
Call call = StaticGlobalContainer.api.getUser(challengerId);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
StaticGlobalContainer.currentUser = response.body();
if (response.code() == 200) {
// 200
// User object returned from server
Log.i("Getting user by id", ACTIVITY_TAG+"_Success");
} else {
// 404 or the response cannot be converted to User.
Log.e("Getting user by id", ACTIVITY_TAG+"_Error:" + response.errorBody());
}
}
#Override
public void onFailure(Throwable t) {
Log.i("HttpRequest - Get user", ACTIVITY_TAG+"_Failure");
}
});
}
This activity ends as soon as user presses a button to go to the next activity:
setUserIdBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StaticGlobalContainer.CURRENT_USER_ID = userIdEditText.getText().toString();
initUserById(Integer.parseInt(StaticGlobalContainer.CURRENT_USER_ID));
startActivity(new Intent(InitActivity.this, MainMenuActivity.class));
finish();
}
});
What happens, if there is a slight delay on the server and it won't respond before user presses the button?
Since activity has already ended, I would expect an exception, but isn't it handled somehow? Like that the activity wouldn't be disposed until callback has been made?
EDIT:
After some thinking, I assume that such callbacks as described above are one of the reason they invented ProgressBars, is that right?
A button triggers an action that should only be invoked once. The button is disabled and hidden in the onClick handler before the action is performed:
someButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
someButton.setEnabled(false);
someButton.setClickable(false);
someButton.setVisibility(View.GONE);
performTaskOnce();
}
});
private void performTaskOnce() {
Log.i("myapp", "Performing task");
//Do something nontrivial that takes a few ms (like changing the view hierarchy)
}
Even though the button is disabled immediately, it is nonetheless possible to trigger multiple "onClick" events by tapping multiple times very quickly. (i.e. performTaskOnce is called multiple times). Is seems that the onClick events are queued before the the button is actually disabled.
I could fix the problem by checking in every single onClick handle whether the corresponding button is already disabled but that seems like a hack. Is there any better way to avoid this issue?
The problem occurs on Android 2.3.6, I cannot reproduce it on Android 4.0.3. But given the rarity of 4.x devices it is not an option to exclude older devices.
You could set a boolean variable to true when the button is clicked and set it to false when you're done processing the click.
This way you can ignore multiple clicks and not having to disable the button possibly avoiding annoying flickering of the button.
boolean processClick=true;
someButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(processClick)
{
someButton.setEnabled(false);
someButton.setClickable(false);
someButton.setVisibility(View.GONE);
performTaskOnce();
}
processClick=false;
}
});
private void performTaskOnce() {
Log.i("myapp", "Performing task");
//Do something nontrivial that takes a few ms (like changing the view hierarchy)
}
In the interest of keeping DRY:
// Implementation
public abstract class OneShotClickListener implements View.OnClickListener {
private boolean hasClicked;
#Override public final void onClick(View v) {
if (!hasClicked) {
onClicked(v);
hasClicked = true;
}
}
public abstract void onClicked(View v);
}
// Usage example
public class MyActivity extends Activity {
private View myView;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView.setOnClickListener(new OneShotClickListener() {
#Override public void onClicked(View v) {
// do clicky stuff
}
});
}
}
Bit late but this might be of use to someone. In my case I am calling another activity so;
Declare a boolean;
boolean clickable;
In the click listener;
if(clickable){
// Launch other activity
clickable = false;
}
Enable when onResume is called;
#Override
public void onResume() {
Log.e(TAG, "onResume");
super.onResume();
clickable = true;
}
You can use RxView(com.jakewharton.rxbinding2.view.RxView) is an extension around RxJava that created by Jake Wharton.
To integrate it to project you should use implementation 'com.jakewharton.rxbinding3:rxbinding:3.1.0'
Simple Java usage:
RxView.clicks(yourButton)
.sample(500, TimeUnit.MILLISECONDS)
.subscribe { action() }
In Kotlin you can create extension function to handle your clicks:
View.singleClick(action: () -> Any) {
RxView.clicks(this)
.sample(500, TimeUnit.MILLISECONDS)
.subscribe { action() }
}
Sample:
Kotlin
yourButton.singleClick({
//do some stuff here
})
Java
SingleClickListenerKt.singleClick(yourButton, () -> {
doSomeStuff();
return null;
});
Note: you can use any RxJava operators like debounce, map, first, etc if you wish.
declare a varieble
and use it as
boolean boo = false;
someButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(boo==false){
someButton.setEnabled(false);
someButton.setClickable(false);
someButton.setVisibility(View.GONE);
boo = true;
}
}
});
by this you prevent multiple clicks on your button
hope it help