Android: Toast won't delay on spinner - android

I want to delay the toast on selected delay times like (15, 30, 60 seconds and no delay) but it won't work. Here's the code:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if(FirstLoad){
FirstLoad = false;
return;
}
Toast.makeText(parent.getContext(), "You chose " +
parent.getItemAtPosition(pos).toString()+ " to delay", Toast.LENGTH_LONG).show();
Message message = new Message();
Bundle bun = new Bundle();
bun.putString("delay", parent.getItemAtPosition(pos).toString());
message.obj = bun;
if (pos == 0) {
handler.sendMessageDelayed(message, 0);
}
else if (pos == 1) {
handler.sendMessageDelayed(message, 15000);
}
else if (pos == 2) {
handler.sendMessageDelayed(message, 30000);
}
else if (pos == 3) {
handler.sendMessageDelayed(message, 60000);
}
//handler.sendMessageDelayed(message, 15000);
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
Help Please.

Try this :
final Toast toast = Toast.makeText(parent.getContext(), "You chose "
+ parent.getItemAtPosition(pos).toString() + " to delay",
Toast.LENGTH_LONG);
Runnable showToastRunnable = new Runnable() {
public void run() {
toast.show();
}
};
if (pos == 0) {
handler.postDelayed(showToastRunnable, 0);
} else if (pos == 1) {
handler.postDelayed(showToastRunnable, 15000);
} else if (pos == 2) {
handler.postDelayed(showToastRunnable, 30000);
} else if (pos == 3) {
handler.postDelayed(showToastRunnable, 60000);
}
Edit:
By the way, I want to transfer this to the send button, i want to delay the toast of "Message sent" according to the delay the user chose. How should I implement it?
How are you fetching the delay? Is it something the user enters in an EditText?
In that case you could just get the delay like this :
int delay = Integer.parseInt(delayEditText.getText().toString());
and then use that delay amount to post the runnable to the handler like this :
handler.postDelayed(showToastRunnable, delay);
You can remove your entire if-else block in this case.

for this you can use custom dialog and hide it after a particular time.
class CustomDialog extends Dialog
{
setContentView(R.layout.dialogxml);
txtview=(TextView)findViewById(R.id.txtmsg);
}
Customdialog dialog= CustomDialog.show();
dialog.hide();

Handler hl_DelayedToast = new Handler(); // scope global
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
{
if(FirstLoad)
{
FirstLoad = false;
return;
}
//if else logic to check the time
// if 0
hl_DelayedToast.postDelayed(mytoastshower,0);
// if 1
hl_DelayedToast.postDelayed(mytoastshower,1000);
}
public Runnable mytoastshower = new Runnable
{
public void run()
{
Toast.show();// show the toast
}
}
hope it helps.

Declare your handler this way:
Hanlder handlder=new Handler() {
public void handleMessage (Message msg) {
Toast.makeText(YOUR_ACTIVITY_CLASS_NAME.this,"You chose"+(Bundle(msg.obj)).getString("delay","DEFAULT_VALUE")+"to delay",Toast.LENGTH_LONG).show();
}
};
Simply, you don't have to use a bundle, but you can call msg.what=THE DELEY TIME.
Also, you can call handler.obtainMessage to get a message. See http://developer.android.com/reference/android/os/Handler.html#obtainMessage%28%29
So every time you send a message, it will be handled here, and thus you call show the toast.
Sorry that I don't have Eclipse installed on this laptop, so I can not test the code. However, I believe it works.

Related

The Timer does not accelerate when it runs for the first time, but the timer accelerates at the next working moments. How can i fix it?

public void startCountdownTimer() {
currentCountdown = startCountdown;
// stopTimer=false;
if (stopTimer == true) {
return;
}
for (int i = 1; i <= startCountdown + 1; i++) {
task = new TimerTask() {
#Override
public void run() {
countdownHandler.post(doA);
}
};
countdownTimer = new Timer();
countdownTimer.schedule(task, i * 1000);
}
}
final Runnable doA = new Runnable() {
#Override
public void run() {
//reset timer when switching to another question
if (currentCountdown != -1 && btn_next.getText().equals("CHECK") && stopTimer != true) {
if (currentCountdown == 0) {
relative_stop.setVisibility(View.INVISIBLE);
currentCountdown = startCountdown;
btn_next.setText("NEXT");
toast = Toasty.warning(getApplicationContext(), "Time's UP", 1000);
toast.show();
toast = Toasty.info(getApplicationContext(), correctAnswer, 1000);
toast.show();
countdownTimer.cancel();
countdownTimer.purge();
}
tv_timer.setText("" + currentCountdown);
currentCountdown--;
}
}
};
I'm trying to make a timer that counts down for 10 seconds, it works normally when it runs for the first time, and when it runs consecutively, the timer caused by delay suddenly speeds up.

Ring user device for video calls with webRTC

I implemented video call in Android using WebRTC.
Call will be made if two users come to same room as their will.
What I want to achieve now, is someone be able to enter a user ID and "Call" him and the other user's phone ring (So there is no problem with webRTC implementation, I just want to implement Ringing behavior).
What I have done so far using Firebase's Realtime database, is that I defined a branch called 'calls', consisting of childs named room name by two user id combination. (so if user1 calls user2, room name will be user1user2).
If user1 calls user2, it sets reqId to 1, and then as user2 listens to any change. he understands that user1 is calling him (and I show incoming call screen) and then it responses by setting reqId to 2, this conversation continues until user2 accepts or cancels the call.
I'm searching for a better solution to achieve this, cause it doesn't seem such a good method and has many problems.
i found the solution.
as if anyone have same question.
for every user, i created a branch called 'call' which is responsible for incoming calls.
and this two functions are what i implemented to perform, or listen for a call:
performCall function:
private DatabaseReference mDatabase;
private static int count = 0;
private void performCall(String s) {
if(count>0)return;
mDatabase = FirebaseDatabase.getInstance().getReference().child("users/"+"USERIDTOCALL"+"/call");
mDatabase.child("roomName").setValue(s);
mDatabase.child("answer").setValue("none");
mDatabase.child("answer").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
switch (Objects.requireNonNull(dataSnapshot.getValue()).toString()){
case "none":
break;
case "yes":
t.cancel();
t.purge();
count =0;
//The Call Should Begin...
break;
case "no":
t.cancel();
t.purge();
count =0;
//RejectedCall
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//Declare the timer
t = new Timer();
count =0;
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mDatabase.child("signal").setValue(new Random().nextInt());
count++;
if(count >= 20){
t.cancel();
t.purge();
count =0;
}
}
}, 0, 2000);
}
and listenForCalls function:
private int count =-1;
private boolean isCalling = false;
Runnable runnable = null;
private boolean callingScreenShowed;
AlertDialog alertDialog;
private void listenForCalls() {
mDatabase = FirebaseDatabase.getInstance().getReference().child("users/"+GlobalVars.userName+"/call");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String answer = dataSnapshot.child("answer").getValue().toString();
if(answer == "yes" || answer =="no") return;
count++;
if(count >= 1){
isCalling = true;
}
if(count == 1 ){
callingScreenShowed= false;
//every 5 seconds check if signaling is active
final int interval = 5000;
Handler handler = new Handler();
runnable = () -> {
if(isCalling){
if(!callingScreenShowed){
//Show A dialog for calling
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage("user with id" + dataSnapshot.child("roomName").getValue() + " Is Calling");
dialog.setTitle("Incoming Call");
dialog.setPositiveButton("YES",
(dialog1, which) -> {
mDatabase.child("answer").setValue("yes");
callingScreenShowed =false;
isCalling = false;
count = -1;
handler.removeCallbacks(runnable);
//Start VideoCall
}
);
dialog.setNegativeButton("cancel", (dialog12, which) -> {
mDatabase.child("answer").setValue("no");
callingScreenShowed =false;
isCalling = false;
count = -1;
handler.removeCallbacks(runnable);
//Clling Rejected
});
alertDialog=dialog.create();
alertDialog.show();
callingScreenShowed = true;
}
}
else {
if(callingScreenShowed){
alertDialog.hide();
}
Log.e("Called","Call Request Ended");
count = -1;
handler.removeCallbacks(runnable);
return;
//Hide Calling Screen
}
isCalling = false;
handler.postDelayed(runnable, interval);
};
runnable.run();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

how to toast message inside the filtering method?

Interface:-
I want to make a toast message, if user did not choose any subject, it will toast message "Please choose subject". There is no error, the issue was I dont know where to put the coding to display the toast message when needed.
Coding:-
#Override
public void onClick(View v) {
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
/*if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
|| spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
}*/
else {
loadFilteredInstitutesList("Advertisement");
}
}
}
You need a move that validation logic up and return without go further if any validation fails.
#Override
public void onClick(View v) {
//add your spinner validity checking here
if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
||
spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
return;
}
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.
this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
loadFilteredInstitutesList("Advertisement");
}
}

Progress bar reset when button is re-clicked [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This Code means that if I Click a button, a progress bar start 0 to 100%. And I want to make the progress bar reset, when I click a button before the progress bar reaches 100%.
Here is a part of my code.
This code is button listener.
public void Cal_btn(View v) {
Message msg;
switch (v.getId()) {
case R.id.Square:
if (Number.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(), "숫자를 입력하세요.", Toast.LENGTH_LONG).show();
} else {
pThread = new ProThread(pHandler);
pThread.setDaemon(true);
pThread.start();
Cal_Result.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
msg = new Message();
msg.what = 1;
msg.arg1 = Integer.parseInt(Number.getText().toString());
mThread.mBackHandler.sendMessage(msg);
}
break;
}
}
And this code is handler.
Handler pHandler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == 3){
if(msg.arg1 == 100){
Cal_Result.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);
}else{
progress.setProgress(msg.arg1);
}
}
}
};
And this code is Thread run code.
class ProThread extends Thread{
int proNum = 0;
Handler pHandler;
ProThread(Handler handler){
pHandler = handler;
}
public void run(){
while(proNum != 100) {
proNum++;
Message msg = new Message();
msg.what = 3;
msg.arg1 = proNum;
pHandler.sendMessage(msg);
try {
Thread.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Add a boolean member variable as a marker for "ProgressBar" started or not.
boolean isProgressBarRun;
When the button is clicked, change the status of this variable.
And if the button is clicked at first time, send a message.
And when you handle the message, re-send the messages every 10 ms in your "public void handleMessage(Message msg)" method.
And your onClick method can be written like below:
boolean isProgressBarRun = false;
...
public void Cal_btn(View v) {
Message msg;
switch (v.getId()) {
case R.id.Square:
if (Number.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(), "숫자를 입력하세요.", Toast.LENGTH_LONG).show();
} else {
if (isProgressBarRun) {
isProgressBarRun = false;
msg = new Message();
msg.what = 4; // to stop the progress bar
mThread.mBackHandler.sendMessage(msg);
msg.what = 3;
msg.arg1 = Integer.parseInt(Number.getText().toString());
mThread.mBackHandler.sendMessage(msg);
} else {
isProgressBarRun = true;
Cal_Result.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
msg = new Message();
msg.what = 1;
msg.arg1 = Integer.parseInt(Number.getText().toString());
mThread.mBackHandler.sendMessage(msg);
}
}
break;
}
}
Your handler can be changed like below:
Handler pHandler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == 4){
progress.setVisibility(View.GONE);
} else {
progress.setProgress(msg.arg1);
Message message = new Message();
message .what = 3;
message .arg1 = msg.arg1 + 1;
pHandler.sendMessageDelayed(message, 10);
}
}
};
In summary, you don't need to implement Thread.
Upper codes are incorrect, just see the concept please.

"Busy" progress dialog causes strange code processing

Let me sum up the situation for you:
I have a button (btnChooseEp), and when you press it an AlertDialog appears.
When something is picked in the AlertDialog, three if statements must be evaluated.
While they are being evaluated, a ProgressDialog appears. It indicates that the app is "busy".
After the evaluation of these statements, the ProgressDialog must disappear.
My problem is described beneath the code.
The entire code block is shown here:
ProgressDialog getTracklistProgressDialog = null;
...
Button btnChooseEp = (Button)findViewById(R.id.btnChooseEp);
btnChooseEp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
final AlertDialog.Builder builder = new AlertDialog.Builder(GA.this);
builder.setTitle(getText(R.string.chooseEpisode));
builder.setItems(episodes, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int pos)
{
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.epNo1);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.epNo2);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.epNo3);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
getTracklistProgressDialog.dismiss();
}
}.start();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
Not sure if needed, but here is the code for the function setTracklist:
public void setTracklist(String string, TextView tv)
{
try
{
tv.setText(getStringFromUrl(string));
}
catch(Exception e)
{
e.printStackTrace();
}
}
And the code for the function getStringFromUrl can be seen here: http://pastebin.com/xYt3FwaS
Now, the problem:
Back when I didn't implement the ProgressDialog thing (which I have from here, btw: http://www.anddev.org/tinytut_-_displaying_a_simple_progressdialog-t250.html), it worked fine - the setTracklist function retrieves a string from a text file on the internet, and sets the text to a TextView. Now, when I have added the ProgressDialog code, and put the original code into the try statement, only a very little part of the text file is added to the TextView - approximately 22-24 characters, not more. The "busy" ProgressDialog shows up just fine. It worked perfectly before; it was more than capable of loading more than 1300 characters into the TextView.
I don't know if it has anything to do with the thread - I have Googled a lot and found no answer.
So, how do I get it to load in all data instead of just a small part?
(By the way, I would love to be able to set the line "setTracklist(epURL, tracklist);" beneath all of the if statements, but then it says it can't resolve "epURL". Seems stupid to write the same line 3 times!)
Updated 25/1 with current code:
final Handler uiHandler = new Handler();
final Button btnChooseEp = (Button)findViewById(R.id.btnChooseEp);
btnChooseEp.setEnabled(false);
btnChooseEp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
builder.setTitle(getText(R.string.chooseEpisode));
builder.setItems(episodes2, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int pos)
{
replay.setVisibility(View.VISIBLE);
replayWeb.setVisibility(View.VISIBLE);
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.gaEpNo1);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.gaEpNo2);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.gaEpNo3);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
uiHandler.post(new Runnable()
{
public void run()
{
getTracklistProgressDialog.dismiss();
}
}
);
}
}.start();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
public void setTracklist2(final String string, final TextView tv)
{
try
{
uiHandler.post(
new Runnable()
{
public void run()
{
try
{
tv.setText(getStringFromUrl(string));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Notes: "replay" and "replayWeb" are just two TextView's. "btnChooseEp" is enabled when another button is pressed.
My guess is that you are getting bizarre behavior because you are invoking a ui method on a non-ui thread.
getTracklistProgressDialog.dismiss();
must be executed on a ui thread. My guess is that it is crashing and your thread is crashing then leaving some of your resources in a bad state. This would explain why you get a varying amount of characters.
I would try creating a final Handler in your onCreate method which would get bound to the uiThread. In that thread, you can then call
uiHandler.post(
new Runnable() {
public void run(){
getTracklistPRogressDialog.dismiss();
}
}
);
This is quick, so it may not be syntactically correct, check your ide.
This is the best i can get from what you've posted. If you post more of the code I can try to run it to give you more help.
Update:
I think I found your problem:
The idea of having another thread is to do the long running work there, but what we have right now actually does the long running work on the ui thread, the opposite of our goal. What we need to do is move the call to getStringFromUrl(url) from the setTracklist call up into the thread. I would rewrite setTracklist as follows:
public void setTracklist(String tracklistContent, TextView tv)
{
try
{
runOnUiThread(
new Runnable() {
public void run() {
tv.setText(tracklistContent);
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Then in your inner onClick method, do this:
public void onClick(DialogInterface dialog, final int pos)
{
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.epNo1);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.epNo2);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.epNo3);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
getTracklistProgressDialog.dismiss();
}
}.start();
}
I'm so, we make the call to the web service/url before we regain ui thread execution. The long running internet retrieval runs on the bg thread and then the ui update happens on the ui thread. Think this should help.

Categories

Resources