Make a Toast in Request Android Studio - java

I want to make a toast but the Toast doesn't get printed
Request r = new Request.Builder().url(url).build();
client.newCall(r).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Toast.makeText(Login.this, "password wrong", Toast.LENGTH_LONG).show();
}

Every UI update in android has to be executed in UI thread:
Run the following code in onFailure
Login.this.runOnUiThread(new Runnable() {
#Override
public void run() { Toast.makeText(Login.this, "password wrong", Toast.LENGTH_LONG).show();
}
});

Related

Firebase not sending any emails

I have configured email verification and password email reset in my firebase project, it used to work fine, I tested it multiple times, but suddenly it stopped working and I am not recieving any email.
I tried checking spam but still, there was nothing.
Here's my code for sending email verification after registering user:
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(RegisterActivity.this, "Please verifiy your email and sign in", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), VerificationActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I also tried to make a button that re-send the email but I get the following message "we have stopped all traffic from this device due to unsual activity"
verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(VerificationActivity.this, "Verification email has been sent, check spam if you are unable to find it", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(VerificationActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
my code for email reset:
auth.sendPasswordResetEmail(email.getText().toString()).addOnSuccessListener(new OnSuccessListener<Void>() { //email is entered by the user
#Override
public void onSuccess(Void unused) {
Toast.makeText(LoginActivity.this, "Reset email sent", Toast.LENGTH_SHORT);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT);
}
});

How to use OnUtteranceProgressListener() with TTS?

I want to Toast a message based on the state of TTS.
For this I used OnUtteranceProgressListener() . But I didn't get the result.
How can I achieve this task ?
Code given below is used to initialize TTS class.
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
//Check if initialisation is successful
if(i==TextToSpeech.SUCCESS)
{
//set Language
int result=textToSpeech.setLanguage(Locale.ENGLISH);
//Check if language is set successfully or not.
if(result==TextToSpeech.LANG_NOT_SUPPORTED||result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(MainActivity.this, "Language not supported", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onDone(String s) {
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(String s) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
else{
Toast.makeText(MainActivity.this, "Initialisation failed", Toast.LENGTH_SHORT).show();
}
}
});
Code given below is used to trigger the event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speak();
}
});
speak() function definition:
private void speak() {
String text="Good Morning";
float pitch=(float)seekBarPitch.getProgress()/50;
float speed=(float)seekBarSpeed.getProgress()/50;
textToSpeech.setPitch(pitch);
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,"UTTERANCE_ID");
}
Toast message do not work in background thread.
So we must run it on UI Thread by using runOnUIThread();

How to call a toast message on success callback in class

I'm working on a POST API using okhttp library. Everything is working fine except I'm unable to find a way to show a simple toast message on it's success callback. How can I call a toast message to the user so he knows wether data is posted on server or not in the success and failure callbacks?
P.S the code below is in a different class not in a activity class.
This is my code:
public DataSource(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(mContext);
mDatabase = mDbHelper.getWritableDatabase();
}
post(URL, jsonData, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i("FAILED", "onFailure: Failed to upload data to server");
//here I want to show toast message
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
//here I want to show toast message
} else {
Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
//here I want to show toast message
}
}
});
Every app has its own special thread that runs UI objects such as View objects; this thread is called the UI thread. Only objects running on the UI thread have access to other objects on that thread. Because tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have access to UI objects. To move data from a background thread to the UI thread, use a Handler that's running on the UI thread or can use android implementation for the same as shown here.
- Case 1
MyActivity.this.runOnUiThread(new Runnable() {
#Override
void run() {
Toast.makeText(MyActivity.this,
"message", Toast.LENGTH_LONG).show();
});
- Case 2
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyActivity.this,
"message", Toast.LENGTH_LONG).show();
}
});
Had it been Main thread you would have used it directly like
Toast.makeText(MyActivity.this,
"message", Toast.LENGTH_LONG).show();
This callback is an asynchronous function, and you can change View just in UI-thread, so Handler will be helpd for you.
....
private final static int MSG_SUCCESS = 0x0001;
private final static int MSG_FAIL = 0x0002;
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what){
case MSG_SUCCESS:
//Toast success
break;
case MSG_FAIL:
//Toast fail
break;
default:
break;
}
}
};
......
......
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
handler.sendEmptyMessage(MSG_SUCCESS);
} else {
Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
handler.sendEmptyMessage(MSG_FAIL);
}
......
You are getting error
java.lang.RuntimeException: Can't create handler inside thread that
has not called Looper.prepare()
Because you're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler,
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
context.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, "SUCCESSFUL", Toast.LENGTH_SHORT).show();
}
});
}
Just send the context of your activity while calling this method:
void methodName(Context c){
post(URL, jsonData, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i("FAILED", "onFailure: Failed to upload data to server");
//here I want to show toast message
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
Toast.makeText(c,"message",Toast.LENGTH_SHORT).show();
//here I want to show toast message
} else {
Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
//here I want to show toast message
}
}
});
}
Try this
TaskActivity.this.runOnUiThread(new Runnable() {
#Override
void run() {
Toast msg = Toast.makeText(TaskActivity.this,
"message", Toast.LENGTH_LONG);
msg.show();
});
Try this
Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
Activity
post(URL, jsonData, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i("FAILED", "onFailure: Failed to upload data to server");
//here I want to show toast message
Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
//here I want to show toast message
Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
} else {
Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
//here I want to show toast message
Toast.makeText(YourActivity.this, "Your Message", Toast.LENGTH_SHORT).show();
}
}
});
Fragment
post(URL, jsonData, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i("FAILED", "onFailure: Failed to upload data to server");
//here I want to show toast message
Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("SUCCESSFUL", "onSuccess: data uploaded");
//here I want to show toast message
Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();
} else {
Log.i("UN SUCCESSFUL", "onFailure: Failed to upload data to server");
//here I want to show toast message
Toast.makeText(getActivity(), "Your Message", Toast.LENGTH_SHORT).show();
}
}
});
Edit
Handler handler = new Handler();
handler.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Your Message", Toast.LENGTH_SHORT).show();
}
});

How to avoid The application may be doing too much work on its main thread

I have two class. One is my SettingsActivity and a class where my volley does the work. In my web service it has a lot of data where it needed to be converted to an ArrayList and will be saved to my Database; I have a two web service to be call after the first one is done before the second one will start it is delayed 1 second. After those things it in my Log it always displays the following
I/Choreographer: Skipped 226 frames! The application may be doing too much work on its main thread.
V/RenderScript: 0x5595d9d0e0 Launching thread(s), CPUs 8
W/art: Suspending all threads took: 20.500ms
W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/data/com.app.myapp/databases/myDB.sqlite' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
I/art: Background partial concurrent mark sweep GC freed 38249(2025KB) AllocSpace objects, 2(968KB) LOS objects, 40% free, 16MB/26MB, paused 569us total 130.628ms
I/Choreographer: Skipped 1528 frames! The application may be doing too much work on its main thread.
I already check if my database is close after using and all of it is closed. But I'm still having the database is leaked message and Skipped xxx frames. I already tried to create a new thread where I call my class in my SettingsActivity when calling the class for my Volley like
btnSync.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
Parameter.parameterOneVolley(SettingsActivity.this, getApplicationContext());
}
});
}
});
After trying this I encounter Can't create handler inside thread that has not called Looper.prepare()
Then also tried using this
runOnUiThread(new Runnable() {
#Override
public void run() {
Parameter.parameterOneVolley(SettingsActivity.this, getApplicationContext());
}
});
But this I'm having an the message Skipped frames. How to solve it? Thank you so much in advance for the help.
In my Paramater class I'm also calling ProgressDialog.
Here's my code for Paramter.parameterOneVolley
public static void parameterOneVolley(final Activity activity, final Context context) {
final ProgressDialog pd = new ProgressDialog(activity);
pd.setMessage("Fetching data....");
pd.show();
initializeDatabase(context);
sqLiteAdapter = new SQLiteAdapter(activity);
regionList = new ArrayList<Region>();
divisionList = new ArrayList<Division>();
final Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray regionArr = response.getJSONArray("Region");
JSONArray divisionArr = response.getJSONArray("Division");
sqLiteAdapter.openToRead();
for(int i = 0; i < regionArr.length(); i++){
JSONObject regionObj = (JSONObject) regionArr.get(i);
Region region = new Region(regionObj.getInt("RegionId"),regionObj.getString("Region"));
regionList.add(region);
if(regionList.size()!=0) {
sqLiteAdapter.insertOrReplaceRegion(regionList);
}
}
for(int i = 0; i < divisionArr.length(); i++){
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
Division division = new Division(divisionObj.getInt("RegionId"),divisionObj.getInt("DivisionId"),divisionObj.getString("Division"));
divisionList.add(division);
if(divisionList.size()!=0) { sqLiteAdapter.insertOrReplaceDivision(divisionList);
}
}
sqLiteAdapter.close();
if(pd != null && pd.isShowing()) {
pd.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
sqLiteAdapter.close();
if(pd != null && pd.isShowing()) {
pd.dismiss();
}
Toast.makeText(context,
e.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "Successfully synced.", Toast.LENGTH_SHORT).show();
//call next web service
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parameterTwoVolley(activity, context);
}
}, 1000);
}
};
final Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(pd != null && pd.isShowing()) {
pd.dismiss();
}
if (error.networkResponse != null) {
Log.d(TAG, "Error Response code: " + error.networkResponse.statusCode);
Toast.makeText(context, error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d(TAG, "Error Response code: Timeout/NoConnection");
Toast.makeText(context, "Timeout/NoConnection", Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Log.d(TAG, "Error Response code: AuthFailureError");
Toast.makeText(context, "AuthFailureError", Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
Log.d(TAG, "Error Response code: ServerError");
Toast.makeText(context, "ServerError", Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
Log.d(TAG, "Error Response code: NetworkError");
Toast.makeText(context, "NetworkError", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Log.d(TAG, "Error Response code: ParseError");
Toast.makeText(context, "ParseError", Toast.LENGTH_SHORT).show();
}
if(pd != null && pd.isShowing()) {
pd.dismiss();
}
}
};
}
I tried adding
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
pd = new ProgressDialog(activity);
pd.setMessage("Fetching data....");
pd.show();
}
}
});
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(pd != null && pd.isShowing()) {
pd.dismiss();
}
Toast.makeText(context, "Successfully synced.", Toast.LENGTH_SHORT).show();
}
});
every time I'm using Progress Dialog and Toast but I still encountering Skipped frames
Also tried using ProgressBar instead and show and hide it but still encountering skipped frames
In Android, only the Main thread (also called the UI thread) can update views. This is because in Android the UI toolkit s not thread safe.
When you try to update the UI from a worker thread Android throws this exception. If you want to update the UI from another Thread use Handler.
final Handler handler=new Handler();
new Thread(new Runnable() {
#Override
public void run() {
//your code
handler.post(new Runnable() {
#Override
public void run() {
Parameter.parameterOneVolley(SettingsActivity.this, getApplicationContext());
}
});
}
}).start();

Facebook invite- Rarely invitation gets delivered after many hours

I have done the task on "Inviting users to the app using facebook" in android, used the below codes as a result if i send the invitation, the invite message rarely delivers after many hours and or else not getting delivered, do anybody know the solution for this?
final ImageView facebook1 = (ImageView) findViewById(R.id.facebook1);
facebook1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Facebook mFacebook = new Facebook( APP_ID );
Bundle params = new Bundle();
params.putString("message", "Prova ");
mFacebook.dialog(Singlemenuitem.this, "apprequests", params, new DialogListener() {
public void onComplete(Bundle values) {
Toast toast = Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_SHORT);
toast.show();
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
public void onCancel() {
Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled",
Toast.LENGTH_SHORT);
toast.show();
}
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
} });

Categories