Method not running in Android - Java - java

I have a problem, whenever I make a method myself and I want to use it, I run into problems. The program does not give an error, but it does not run. If anyone knows what the problem is, please help me.
public class MainActivity extends AppCompatActivity {
List item
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomToast1(" show text");
}
public void CustomToast1(String text) {
Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
View view1 = toast.getView();
TextView txt1 = view1.findViewById(android.R.id.message);
view1.setBackgroundColor(Color.argb(50, 0, 0, 0));
txt1.setTextSize(24);
txt1.setTextColor(Color.BLUE);
txt1.setWidth(700);
txt1.setGravity(Gravity.CENTER_VERTICAL);
txt1.setCompoundDrawablePadding(40);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}

You can't access the toast view from the toast, to protect the users.
if you want to do this you should use this code:
private void CustomToast1(String text) {
Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
View view1 = toast.getView();
TextView txt1 = (TextView) view1.findViewById(androidx.appcompat.R.id.message);
view1.setBackgroundColor(Color.argb(50, 90, 90, 0));
txt1.setTextSize(24);
txt1.setTextColor(Color.BLUE);
txt1.setWidth(700);
txt1.setGravity(Gravity.CENTER_VERTICAL);
txt1.setCompoundDrawablePadding(40);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
}
toast.show();
}
if the statement is true then it will display it with it
but for you probably it will display as default but it won't crash.

Related

Android - Custom Toast Class

I am trying to create a class that it´s supossed to show a toast every time that an object of this class is instaciated.
I want to do this so that I don´t have the same toast code repeated in every activity.
public class Toast extends android.widget.Toast {
String toast_text;
Context toast_context;
public Toast(String toast_text, Context toast_context) {
this.toast_text = toast_text;
this.toast_context = toast_context;
Toast toast = android.widget.Toast.makeText(this.toast_context.this, this.toast_text, Toast.LENGTH_LONG);
ViewGroup view = (ViewGroup) toast.getView();
view.setBackgroundResource(R.drawable.background_global);
TextView messageTextView = (TextView) view.getChildAt(0);
messageTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
messageTextView.setTextSize(35);
Typeface face_font = Typeface.createFromAsset(getAssets(), "res/font/aldrich.ttf");
messageTextView.setTypeface(face_font);
messageTextView.setTextColor(Color.CYAN);
toast.show();
}
}
These are the following erros:
On the constructor: "There is no default constructor available in "android.widget.toast";
On the first error: " ')' expected";
On the second error: "Cannot resolve method "getAssets" ".
Use toast_context that you receive through constructor to create toast and access asset
Toast toast = android.widget.Toast.makeText(toast_context, toast_text, Toast.LENGTH_LONG);
Typeface face_font = Typeface.createFromAsset(toast_context.getAssets(), "res/font/aldrich.ttf");
Beside this, You should use other name than Toast to create custom toast
class MyToast extends android.widget.Toast {
public MyToast(String toast_text, Context toast_context) {
super(toast_context);
...
}
}

Creating a notification inside DialogFragment class doesn't work! (Android)

I've been searching around and tried different solutions but I can't seem to get this to work.
I have a MainActivity with a list and an "Add" button. When i click the addbutton i open a DialogFragment. In the dialog user inputs data and press "add" and i want a notification that says "xxxx has been added to list" but it never shows.
I have a seperate class for AddDialog which looks like this:
public class AddDialogFragment extends DialogFragment {
Button btnAdd;
Button btnCancel;
TextView etNewSerial, etNewBrand, etNewModel;
String newSerial, newBrand, newModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.dialog_add, container, false);
getDialog().setTitle("Add new serial!");
btnAdd = (Button) rootView.findViewById(R.id.btnAddNew);
etNewSerial = (TextView) rootView.findViewById(R.id.etNewSerial);
etNewBrand = (TextView) rootView.findViewById(R.id.etNewBrand);
etNewModel = (TextView) rootView.findViewById(R.id.etNewModel);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newSerial = etNewSerial.getText().toString();
newBrand = etNewBrand.getText().toString();
newModel = etNewModel.getText().toString();
String url = "MY_VOLLEY_URL"
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
int icon = 0;
CharSequence notiText = "Item Added!";
long notiTime = System.currentTimeMillis();
CharSequence notiTitle = "Item Added!";//Titel
CharSequence notiContent = newSerial + " added!";
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notBuilder = new NotificationCompat.Builder(getActivity());
notBuilder.setSmallIcon(icon)
.setTicker(notiText)
.setWhen(notiTime)
.setAutoCancel(true)
.setContentText(notiContent)
.setContentTitle(notiTitle)
.setContentIntent(pendingIntent);
Notification notification = notBuilder.build();
NotificationManager myNotificationManager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationManager.notify(1, notification);
getDialog().dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
});
return rootView;
}
}
But the notification never shows. I've been trying to replace the "getActivity()" with different methods for context but it doesn't seem to matter. Does anyone has some tips to make this possible?
I wonder you are getting this error because your are passing 0 as the resourceId for the small icon (setSmallIcon). Maybe, NotificationManager is ignoring this notification since it can not built properly (there's no resource with 0 as ID.
So, try to change this:
notBuilder.setSmallIcon(icon)
....
To:
notBuilder.setSmallIcon(android.R.color.transparent)
....
I use android.R.color.transparent as example since you are not interested in show any icon anyway. But you can change to any color/drawable etc...

How to show download progress in app

I've gotten my app to download content from a website but the intent asks you to open the link in the browser and downloads it from there. I wish to change that so when i tap the download button, instead of the intent directing to the browser it opens a popup in my app and shows the download progress.
How am I able to achieve this?
I have searched around stackoverflow and have only found ways that don't work for me. Here is my code -
txtLink = (EditText) findViewById(R.id.input_package);
btnOpenLink = (ImageButton) findViewById(R.id.download);
btnOpenLink.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String page = txtLink.getText().toString();
if (!TextUtils.isEmpty(page)) {
Uri uri = Uri.parse(defaultLink + page);
// Success Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Your download should start shortly");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else {
// Fail Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Please enter a package name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
});
Could someone explain what is the best way to create a popup download progress?
Because i have an input field where one can enter the second part of the url and it downloads that. Eg- download.com/ but the user enters "download" so when he taps the button it changes to download.com/download and it downloads from that url.
Thanks
You can do something like this..
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Write your download logic under the doInBackground method of Asynctask.This should solve your purpose and it wont even block UI tread..

How to display a Toast message in the top of the page in my android application

I m using the following line to make a Toast message displayed in my android application
Toast.makeText(InitActivity.this, InitActivity.this.getResources().getString(R.string.invalid_pin_code), Toast.LENGTH_SHORT).show();
But this message is displayed in the bootom of the page.
And I want to display it below an EditText in my page.
How to make that?
You need add this as programmatically like this in your code:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
Try this :
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.
Offical Document Source Here
For custom Toast check here
For making custom position follow this
EDIT : For making position on particular View try this:
This code in your onCreate() method
editText1 = (EditText)rootView.findViewById(R.id.editText1);
button1 = (Button)rootView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
makeToast("Hello", editText1);
}
});
And add this makeToast(String,View) method
public void makeToast(String text, View v) {
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
int xOffset = 0;
int yOffset = 0;
Rect gvr = new Rect();
View parent = v;// // v is the editText,
// parent is the rectangle holding it.
if (parent.getGlobalVisibleRect(gvr)) {
View root = v.getRootView();
int halfwayWidth = root.getRight() / 2;
int halfwayHeight = root.getBottom() / 2;
// get the horizontal center
int parentCenterX = ((gvr.right - gvr.left) / 2) + gvr.left;
// get the vertical center
int parentCenterY = (gvr.bottom - gvr.top) / 2 + gvr.top;
if (parentCenterY <= halfwayHeight) {
yOffset = -(halfwayHeight - parentCenterY);// this image is
// above the center
// of gravity, i.e.
// the halfwayHeight
} else {
yOffset = parentCenterY - halfwayHeight;
}
if (parentCenterX < halfwayWidth) { // this view is left of center
// xOffset = -(halfwayWidth -
// parentCenterX); } if
// (parentCenterX >=
// halfwayWidth) {
// this view is right of center
xOffset = parentCenterX - halfwayWidth;
}
}
Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, xOffset, yOffset);
toast.show();
}
Displays and centralize your toast at the top
Toast toast = Toast.makeText(getApplicationContext(),"Network issue! Check your internet", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
View view = toast.getView();
view.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN); toast.show();
You should set gravity of toast. Use this:
Toast toast = Toast.makeText(InitActivity.this,
InitActivity.this.getResources().getString(R.string.invalid_pin_code),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
you can create your own custom toast using, like:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);<----- toast location on screen
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

How can I transform this into a method/class so it can be reusable?

I want to use this in lots of places in my code and there will be a lot of repetition, but my knowledge in java is not sufficient enough to make this work.
Toast myToast = Toast.makeText(net.asdqwe.activities.Signup.this, configurationz.ERROR_MESSAGES_SIGNUP_USER_NAME_MIN_LENGTH_PROBLEM, Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
I wanna be able to use it this way:
ToastMaker(short duration (//or long), configurationz.ERROR_MESSAGE (//of my choice), configurationz.COLORS_TOAST_TEXT_COLOR(//or some other variable), configurationz.COLORS_TOAST_BACKGROUND_COLOR(//or some other variable), 30(//text size), gravity)
something like this
ToastMaker(length, errorMessage, textColor, backgroundColor, textSize, gravity)
the one thing that concerns me the most is that the following piece of code is going to change for every class, and I do not know how to obtain that dynamically
net.asdqwe.activities.Signup.this
Actually I can make the text color, size and background a general setting for the entire app (which makes sense), so we are left with this:
ToastMaker(length, errorMessage, gravity)
as the final desired result
EDIT: I've answered my question with the working code, that I generated after reading all the answers
Do this way
I putted in runOnUi() method so you can call it from Asynctask/background thread
For long time
public void tong(Context mContext, final String msg) {
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast myToast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
});
}
For short time
public void ting(final Context mContext, final String msg) {
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast myToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
});
}
if want to declare it in saperet class the
class YourClass{
public void showToast(Context context){
Toast myToast = Toast.makeText(context, configurationz.ERROR_MESSAGES_SIGNUP_USER_NAME_MIN_LENGTH_PROBLEM, Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
}
use in other class like this
YourClass myClass=new YourClass();
myClass.showToast(mContext);
You can also pass other parameter with context (e.g. message).
How about make one static method like:
public static void ToastMaker(length, errorMessage, textColor, backgroundColor, textSize, gravity)
Need to add context as parameter though. Just put your code in that method and that about it. You may even use custom layout
refer to this link: Custom toast message in all screens?
Hope this makes it bit more clear.
Regards
you can simple use this:
1) First make a Common class named DisplayToast.
and in this class make method like
public void showToast(Context context){
Toast myToast = Toast.makeText(context, configurationz.ERROR_MESSAGES_SIGNUP_USER_NAME_MIN_LENGTH_PROBLEM, Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
Now whenever you want to access this method in any class then you should make object of this class like:
DisplayToast dt = new DisplayToast();
now call that method
dt.showToast(context);
2) You can also make static method for that like:
public static void showToast(Context context){
Toast myToast = Toast.makeText(context, configurationz.ERROR_MESSAGES_SIGNUP_USER_NAME_MIN_LENGTH_PROBLEM, Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(20);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
And you can use this in your class like
DisplayToast.showToast(context);
Thank you everyone, thanks to your help, this is what I created and it works perfectly:
public class ToastMaker extends Activity {
public void toast(Context context, final String message, Configurationz configurationz, int duration) {
Toast myToast = Toast.makeText(context, message , duration);
myToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
TextView tv = (TextView) myToast.getView().findViewById(android.R.id.message);
tv.setTextColor(Color.parseColor(configurationz.COLORS_TOAST_TEXT_COLOR));
tv.setTextSize(configurationz.TOAST_TEXT_SIZE);
myToast.getView().setBackgroundColor(Color.parseColor(configurationz.COLORS_TOAST_BACKGROUND));
myToast.show();
}
}
Im using it this way:
ToastMaker toastMaker = new ToastMaker();
toastMaker.toast(net.asdqwe.activities.Signup.this, configurationz.ERROR_MESSAGES_SIGNUP_USER_NAME_MIN_LENGTH_PROBLEM, configurationz, Toast.LENGTH_SHORT);

Categories

Resources