I am a beginner in this field.
How can i access a method from one package to another.
For example:
package add;
public class Addfunction {
int a,b,sum;
public int add(int x,int y)
{
a=x;
b=y;
sum=a+b;
return sum;
}
}
in my second package
package com.example.demoo;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int Result;
Addfunction addfunction=new Addfunction();
Result=addfunction.add(5, 10);
Toast.makeText(getApplicationContext(), Result , Toast.LENGTH_LONG).show();
}
}
while running it shows Unfortunately app is stop.
please help me to solve this.
There's nothing wrong in how you access the Addfunction class. But consider two things.
First, you must add an import for the Addfunction class before the MainActivity class definition:
import add.Addfunction;
although you probably already have that, because it wouldn't compile otherwise.
Second, you are probably using this makeText:
static Toast makeText(Context context, int resId, int duration)
Make a standard toast that just contains a text view with the text from a resource.
instead of this:
static Toast makeText(Context context, CharSequence text, int duration)
Make a standard toast that just contains a text view.
Note the second parameter is an int in the first case which refers to a resource. And you are just passing the result of your computation which is probably an invalid resource id.
You may want to try to build a message in a String object and pass it to makeText, like this:
String msg = "Result: " + Result;
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
Related
First of all, I know separately how to make custom method to show Toast & show String which extend from resource.
See:
private void showToast(CharSequence text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
And for Extend String Resource:
private void setStringResource(int resource) {
getResources().getString(resource);
}
But, I want to use something like this:
showToast(setStringResource(R.string.please_check_connection));
And, it gives compiler error.
How can I do that? Please reply fast. Thank you.
When you are calling your setStringResource, you aren't returning any value. Modify your method to the following:
private String setStringResource(int resource) {
return getResources().getString(resource);
}
Now when you call this method when creating your Toast, the method returns a String.
Change your method to the following:
private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private String setStringResource(int resource) {
return getResources().getString(resource);
}.
I'm following tutorials on how to put functions that are used frequently in activities all in one place.
For example, a toast message that comes up throughout my project, instead of having the function in each and every activity, just having it called in one place, GlobalFunctions.java.
So, I get it with simple functions, for example, in GlobalFunctions.java :
public class GlobalFunctions {
public void simpleMessage() {
System.out.println("simpleMessage text goes here");
}
}
And the I call it like this from Activity1:
GlobalFunctions simplemessage = new GlobalFunctions();
simplemessage.simpleMessage();
But what about? :
public class GlobalFunctions {
public void simpleMessage() {
Toast.makeText(getApplicationContext(), "simpleMessage text goes here", Toast.LENGTH_LONG).show();
}
}
I've looked at several posts including getApplicationContext() error Android and no matter what I put in the Context part of Toast I get a Cannot resolve method message. Also if there's any good tutorials for Dummies on this subject I'd be grateful.
The key is static .
Static values allow you to use static methods variables ..etc in whole project.
You can use following concept:
public static class GlobalFunctions {
public static void simpleMessage(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
And you have to invoke it like:
GlobalFunctions.simpleMessage(/*YourActivity.this*/ /*or*/ /*getActivity()*/, "toast");
One solution would be to pass the Context as a parameter from the Activity or Fragment.
And instead of instantiating GlobalFunctions, writing and using static methods can be a better approach.
Create a Java Utils class:
public class Utils {
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
}
// for example on the Activity code
Utils.showToast(this, "This is the toast text");
Keeping context in field beyond activity can be reason of memory leak, but there is some workaround.
You can create Singleton with application or application context and initialize it in onCreate in your custom application class. But you have to remember that you can't use this context to build views - it is not stylized.
Other way is just pass context as argument.
Sorry for missing code, response from phone :)
try this Create class like this to pass Context and Toast message as parameter like this
public class GlobalFunctions {
public static void simpleMessage(Context context,String message) {
Toast.makeText(Context, message, Toast.LENGTH_LONG).show();
}
}
call this function like this
GlobalFunctions.simpleMessage(YourActivity.this,"your Mesaage");
I have a bunch of EditTexts that are set up with int Strings to capture their length. I want to show the lengths in LogCat to confirm they have been set up correctly. I read about using LogCat, tags and how to filter but need some advice on how to add Log code to get output to LogCat.
Here is an example of the int String I am looking to calculate length for:
public class CardViewActivity extends AppCompatActivity {
private String tag = "CLOCKS";
private ListenerEditText eListenerEditText;
eListenerEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
int stringNotes2 = eListenerEditText.getText().toString().trim().length();
Log.d("CLOCKS", String.valueOf(stringNotes2));
Log.d() must be called in somewhere like onCreate(..) {..} or some type of method.
for example,
// This is wrong
public class Hello {
Log.d("hello","hi");
...
}
Make sure you call methods in some type of methods.
// This is correct
public class Hello extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Hello","Hi");
...
}
...
}
Hope this helps
You shoud declare your log tag:
private static final String MYAPPTAG= YourActivity.class.getName();
Then you put the log code in a method:
Log.d(MYAPPTAG, String.valueOf(stringDueDate));
You will need to make sure you set your filter properly in logCat settings.
I suggest you to concatenate with a string to make sure something prints to the console just incase the value is null, for example:
Log.d(MYAPPTAG, "stringDueDate = " + stringDueDate);
Try this -
public class CardViewActivity extends AppCompatActivity {
private static final String TAG = "CLOCKS";
private ListenerEditText eListenerEditText;
eListenerEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
int stringNotes2 = eListenerEditText.getText().toString().trim().length();
Log.d(TAG, "Length - " + stringNotes2));
}
}
If this doesn't work then there must be something wrong with your listener. I'll highly recommend to use TextWatcher on EditText over KeyListener.
Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.
Log.i(String tag, String msg);
I have an app that uses custom Exceptions, such as this:
public class SomeException extends Exception{
private int iCode;
private String iMessage;
public SomeException(){
iCode = 201;
iMessage = **//Get the localized string R.string.error_201??**
}
#Override
public String getMessage() {
return iMessage;
}
#Override
public int getCode() {
return iCode;
}
}
Obviously, I want lo localize the error message. I have possible solutions but non of them satisfy me.
1) Pass "Context" to the constructor, and do ctx.getString(R.string.error_201)
--> Fail, as this Exceptions are sometimes thrown from MODEL classes, so they don't have a Context
2) Pass "Context" when retriveing the message in getMessage() function,
--> Fail, It's necesary to override the super method, to work as all other Exceptions.
Solution I have now: All activities in my app have this onCreate:
public void onCreate(...){
Utils.RESOURCES = getResources();
...
}
Very dirty code... I don't like the solution. My question is then,: is there a way to access the resources without the Context? And most important, How would an application such as mine solve this problem?
What about
public class MyException extends Exception {
private int iCode;
public MyException(int code) {
this.iCode = code;
}
#Override
public String getMessage() {
return "MyException code " + String.valueOf(iCode);
}
public String getLocalizedMessage(Context ctx) {
String message;
if (iCode == 201)
message = ctx.getString(R.string.error_201);
else if (iCode == 202)
message = ctx.getString(R.string.error_202);
// ...
}
}
Even if there was way to access context in different way, you should not do it. If you need to emit exceptions where you cannot pass Context, you should be able to access context before you display such error. I cannot see reason why you should create localized error messages from constructor. You can log to logcat not localized versions if you need. And where you want to display something in UI, you should have context at hand.
You can access only system wide resources without Context.
You need a Context, so I would suggest You to get it as soon as possible, and make it available through a static method or variable. You do the same thing in every Activity, but there is a cleaner method. You should make a custom Application, and override its onCreate() to make the resources public:
public class App extends Application {
private static Resources myResources;
#Override
public void onCreate() {
myResources = getBaseContext().getResources();
super.onCreate();
}
public static Resources getMyResources(){
return myResources;
}
}
The other thing you have to do is to set the Application in your manifest:
<application
android:name="{your_package}.App"
...
Now you can access the resources in all of your Activity without any preparation. Your custom Exception class could also use the externalized resources.
I am working on the task that requires the password field (i.e.the Edit Text) to hide user input using asterisks(*) rather than dots(.). Currently it shows as dots.
Kindly tell me the way to do it if its possible using android's native methods. Or please post the code to do it if anyone has already done that.
Thanks in advance..
Very late answer, and I'm sure you don't care anymore, but someone else might.
Initialize EditText Field .
EditText UPL =(EditText) findViewById(R.id.UserPasswordToLogin) ;
UPL.setTransformationMethod(new AsteriskPasswordTransformationMethod());
Then Create a new java class ,Called AsteriskPasswordTransformationMethod.java Which extends PasswordTransformationMethod
Here is code :
import android.text.method.PasswordTransformationMethod;
import android.view.View;
public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return new PasswordCharSequence(source);
}
private class PasswordCharSequence implements CharSequence {
private CharSequence mSource;
public PasswordCharSequence(CharSequence source) {
mSource = source; // Store char sequence
}
public char charAt(int index) {
return '*'; // This is the important part
}
public int length() {
return mSource.length(); // Return default
}
public CharSequence subSequence(int start, int end) {
return mSource.subSequence(start, end); // Return default
}
}
};
public final void setTransformationMethod (TransformationMethod method)
Since: API Level 1
Sets the transformation that is applied to the text that this TextView is displaying.
Related XML Attributes
android:password
android:singleLine
allows you to change any char
I would imagine you could override the listener class methods to modify the text to display so that it reads as "*", but keep the actual string in the background somewhere. So each time the user enters a letter, you add it to your cumulative "password" string, and instead, replace that character in the displayed string with *