Issue
I have a class named MyPrimaryClass, this class has a button witch when pressed, creates an Intent with the class myClassForResult.
I use this to start it:
startActivityForResult(myIntentOfMyClassForResult, ACTIVITY_EDIT_BTEXT);
Both MyPrimaryClass, and myClassForResult extends Activity.
So, when I call Toast.makeText within the myClassForResult, with the text parameter of R.string.my_resource_string, it gives me Force Close!
I have tried this:
Context c = myClassForResult.this;
Toast toast = Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT);
toast.show();
Also this: c = getApplicationContext()
Also this: c = getBaseContext()
Also this:
Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
R.string.my_resource_string,
Toast.LENGTH_SHORT);
toast.show();
If I use an inline string, like "My toast Text!", it works. But i need to get a string from the resources.
-Problem solved:
To solve the problem I changed the duration of the Toast to Toast.LENGTH_LONG
The string R.string.my_resource_string value is "The title is empty"
When I change its value to "The title", it worked properly, so I guess the string was too long for the Toast.LENGTH_SHORT duration.
But when i change the duration to Toast.LENGTH_LONG, I could use the long string.
Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
R.string.my_resource_string,
Toast.LENGTH_LONG);
toast.show();
Solution
One thing to note:
Toast toast = Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT);
toast.show();
Can be simplified into:
Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT).show();
This saves you an object reference that you do not need.
One thing you need to understand is that whenever you reference you R in your package (not android.R.) you will have access to your resources as long as you have Context.
Update
After realizing what you are using this for I would recommend that you change your approach, while this is in fact possible, your approach isn't ideal for something so simple.
The method startActivityForResult(xx) is typically when you want to start an application that is outside of your package for a result.
For instance: if I wanted to retrieve a barcode from a product, then I'd start an Intent to that barcode class, indirectly through an action. Then I'd retrieve the data through using onActivityResult(xx).
it makes No Sense to do this for your own classes.
Answered By - JoxTraex
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.